<?php
declare(strict_types=1);

namespace App\Modules\ParentPortal\Services;

use App\Core\App;
use App\Core\EventBus;
use App\Modules\ParentPortal\Models\ParentAccount;

class ParentService
{
    public static function createParent(array $data): ParentAccount
    {
        $parent = ParentAccount::create($data);

        EventBus::dispatch('parent.created', [
            'parent_id' => (int) $parent->id,
            'name'      => $data['full_name_ar'],
            'phone'     => $data['phone'],
        ]);

        return $parent;
    }

    public static function linkPlayer(int $parentId, int $playerId, string $relationship = 'parent', bool $isPrimary = false): void
    {
        $db = App::getInstance()->db();

        $existing = $db->selectOne(
            "SELECT id FROM parent_player_links WHERE parent_id = ? AND player_id = ?",
            [$parentId, $playerId]
        );
        if ($existing) return;

        if ($isPrimary) {
            $db->query("UPDATE parent_player_links SET is_primary_contact = 0 WHERE player_id = ?", [$playerId]);
        }

        $db->insert('parent_player_links', [
            'parent_id'            => $parentId,
            'player_id'            => $playerId,
            'relationship'         => $relationship,
            'is_primary_contact'   => $isPrimary ? 1 : 0,
            'can_view_evaluations' => 1,
            'can_view_attendance'  => 1,
            'can_view_medical'     => 1,
            'can_view_financials'  => 1,
            'can_approve_group_change' => 0,
            'created_at'           => date('Y-m-d H:i:s'),
        ]);

        EventBus::dispatch('parent.player_linked', [
            'parent_id' => $parentId,
            'player_id' => $playerId,
        ]);
    }

    public static function unlinkPlayer(int $parentId, int $playerId): void
    {
        $db = App::getInstance()->db();
        $db->delete('parent_player_links', 'parent_id = ? AND player_id = ?', [$parentId, $playerId]);
    }

    public static function getPlayerDashboard(int $parentId, int $playerId): array
    {
        $db = App::getInstance()->db();

        $link = $db->selectOne(
            "SELECT * FROM parent_player_links WHERE parent_id = ? AND player_id = ?",
            [$parentId, $playerId]
        );
        if (!$link) return [];

        $player = $db->selectOne("SELECT * FROM players WHERE id = ?", [$playerId]);
        if (!$player) return [];

        $result = ['player' => $player, 'permissions' => $link];

        if ($link['can_view_attendance']) {
            $result['recent_attendance'] = $db->select(
                "SELECT sa.*, ts.session_date, ts.start_time, ts.end_time
                 FROM session_attendance sa
                 JOIN training_sessions ts ON ts.id = sa.session_id
                 WHERE sa.player_id = ?
                 ORDER BY ts.session_date DESC LIMIT 20",
                [$playerId]
            );
        }

        if ($link['can_view_evaluations']) {
            $result['evaluations'] = $db->select(
                "SELECT * FROM player_evaluations WHERE player_id = ? AND parent_visible = 1 ORDER BY evaluation_date DESC LIMIT 10",
                [$playerId]
            );
        }

        if ($link['can_view_medical']) {
            $result['medical'] = $db->select(
                "SELECT * FROM player_medical_records WHERE player_id = ? ORDER BY exam_date DESC LIMIT 5",
                [$playerId]
            );
            $result['injuries'] = $db->select(
                "SELECT * FROM player_injuries WHERE player_id = ? AND status IN ('active', 'recovering') ORDER BY occurred_date DESC",
                [$playerId]
            );
        }

        if ($link['can_view_financials']) {
            $result['subscriptions'] = $db->select(
                "SELECT * FROM activity_subscriptions WHERE player_id = ? ORDER BY subscription_month DESC LIMIT 6",
                [$playerId]
            );
        }

        $result['achievements'] = $db->select(
            "SELECT pa.*, ad.name_ar, ad.icon, ad.badge_color
             FROM player_achievements pa
             JOIN achievement_definitions ad ON ad.id = pa.achievement_id
             WHERE pa.player_id = ?
             ORDER BY pa.earned_at DESC LIMIT 10",
            [$playerId]
        );

        $result['groups'] = $db->select(
            "SELECT tg.*, gm.status AS membership_status
             FROM group_memberships gm
             JOIN training_groups tg ON tg.id = gm.group_id
             WHERE gm.player_id = ? AND gm.status = 'active'",
            [$playerId]
        );

        return $result;
    }

    public static function notifyParents(int $playerId, string $type, string $title, string $body): void
    {
        $db = App::getInstance()->db();
        $parents = $db->select(
            "SELECT pa.id, pa.phone FROM parent_player_links ppl
             JOIN parent_accounts pa ON pa.id = ppl.parent_id
             WHERE ppl.player_id = ? AND pa.is_active = 1",
            [$playerId]
        );

        foreach ($parents as $parent) {
            $db->insert('parent_notifications_log', [
                'parent_id'         => (int) $parent['id'],
                'player_id'         => $playerId,
                'notification_type' => $type,
                'title_ar'          => $title,
                'body_ar'           => $body,
                'is_read'           => 0,
                'channel'           => 'sms',
                'sent_at'           => date('Y-m-d H:i:s'),
                'created_at'        => date('Y-m-d H:i:s'),
            ]);
        }
    }
}
