<?php

namespace App\Filament\Pages;

use Filament\Pages\Page;

class FamilyTreePage extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-share';
    protected static ?string $navigationLabel = 'Pokok Keluarga';
    protected static ?string $title = 'Salasilah Keluarga';

    protected static string $view = 'filament.pages.family-tree-page';

    public function getTreeData()
    {
        $users = \App\Models\User::where('id', '!=', 1)->get();
        $marriages = \App\Models\Marriage::all();
        
        $data = [];
        
        foreach ($users as $user) {
            // Get spouses (pids)
            $pids = [];
            if ($user->gender === 'Lelaki') {
                $pids = $marriages->where('husband_id', $user->id)->pluck('wife_id')->toArray();
            } else {
                $pids = $marriages->where('wife_id', $user->id)->pluck('husband_id')->toArray();
            }

            $phoneFormatted = $user->phone_number ? preg_replace('/[^0-9]/', '', $user->phone_number) : null;
            if ($phoneFormatted && str_starts_with($phoneFormatted, '0')) {
                $phoneFormatted = '6' . $phoneFormatted;
            }

            $data[] = [
                'id' => $user->id,
                'pids' => $pids,
                'mid' => $user->mother_id,
                'fid' => $user->father_id,
                'name' => $user->name,
                'gender' => $user->gender === 'Lelaki' ? 'male' : 'female',
                'jantina' => $user->gender,
                'umur' => $user->dob ? \Carbon\Carbon::parse($user->dob)->age . ' tahun' : '-',
                'status' => $user->is_alive ? 'Masih Hidup' : 'Meninggal Dunia',
                'phone' => $user->phone_number ?: '',
                'call_url' => $user->phone_number ? 'tel:' . $user->phone_number : '',
                'wa_url' => $phoneFormatted ? 'https://wa.me/' . $phoneFormatted : '',
                'img' => $user->profile_photo_path ? asset('storage/' . $user->profile_photo_path) : 'https://ui-avatars.com/api/?name=' . urlencode($user->name) . '&background=1b4332&color=fff',
                'tags' => [$user->gender === 'Lelaki' ? 'male' : 'female'],
            ];
        }
        
        return $data;
    }
}
