<?php
declare(strict_types=1);

namespace App\Modules\ParentPortal\Models;

use App\Core\Model;
use App\Core\App;

class ParentAccount extends Model
{
    protected static string $table = 'parent_accounts';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;

    protected static array $fillable = [
        'member_id', 'full_name_ar', 'full_name_en', 'phone', 'secondary_phone',
        'email', 'national_id', 'relationship', 'pin_hash', 'is_active',
        'last_login_at', 'notification_preferences_json',
    ];

    public static function getRelationshipTypes(): array
    {
        return [
            'father'   => 'أب',
            'mother'   => 'أم',
            'guardian' => 'ولي أمر',
            'parent'   => 'والد/والدة',
        ];
    }

    public function getLinkedPlayers(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT p.*, ppl.relationship, ppl.is_primary_contact,
                    ppl.can_view_evaluations, ppl.can_view_attendance, ppl.can_view_medical, ppl.can_view_financials
             FROM parent_player_links ppl
             JOIN players p ON p.id = ppl.player_id
             WHERE ppl.parent_id = ?
             ORDER BY p.full_name_ar ASC",
            [(int) $this->id]
        );
    }

    public static function findByPhone(string $phone): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne("SELECT * FROM parent_accounts WHERE phone = ? AND is_active = 1", [$phone]) ?: null;
    }

    public static function getForPlayer(int $playerId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT pa.*, ppl.relationship, ppl.is_primary_contact
             FROM parent_player_links ppl
             JOIN parent_accounts pa ON pa.id = ppl.parent_id
             WHERE ppl.player_id = ? AND pa.is_active = 1
             ORDER BY ppl.is_primary_contact DESC",
            [$playerId]
        );
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = ["pa.is_active = 1"];
        $params = [];

        if (!empty($filters['search'])) {
            $where[] = "(pa.full_name_ar LIKE ? OR pa.phone LIKE ? OR pa.national_id LIKE ?)";
            $params[] = '%' . $filters['search'] . '%';
            $params[] = '%' . $filters['search'] . '%';
            $params[] = '%' . $filters['search'] . '%';
        }

        $whereClause = implode(' AND ', $where);
        $countRow = $db->selectOne("SELECT COUNT(*) AS total FROM parent_accounts pa WHERE {$whereClause}", $params);
        $total = (int) ($countRow['total'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $data = $db->select(
            "SELECT pa.*, (SELECT COUNT(*) FROM parent_player_links WHERE parent_id = pa.id) AS players_count
             FROM parent_accounts pa
             WHERE {$whereClause}
             ORDER BY pa.full_name_ar ASC
             LIMIT ? OFFSET ?",
            array_merge($params, [$perPage, $offset])
        );

        return [
            'data' => $data,
            'pagination' => ['total' => $total, 'per_page' => $perPage, 'current_page' => $page, 'last_page' => (int) ceil($total / $perPage)],
        ];
    }
}
