<?php
declare(strict_types=1);

namespace App\Modules\ParentPortal\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\ParentPortal\Models\ParentAccount;
use App\Modules\ParentPortal\Services\ParentService;

class ParentController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('parent.view');
        $filters = ['search' => trim((string) $request->get('q', ''))];
        $page = max(1, (int) $request->get('page', 1));
        $result = ParentAccount::search($filters, 25, $page);

        return $this->view('ParentPortal.Views.index', [
            'rows'       => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
        ]);
    }

    public function create(Request $request): Response
    {
        $this->authorize('parent.manage');
        return $this->view('ParentPortal.Views.create', [
            'relationships' => ParentAccount::getRelationshipTypes(),
        ]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('parent.manage');

        $rules = [
            'full_name_ar' => 'required|string|max:200',
            'phone'        => 'required|string|max:30',
            'relationship' => 'required|string',
        ];

        $errors = $this->validate($request->all(), $rules);
        if ($errors) return $this->redirect('/parents/create')->withError('يرجى تصحيح الأخطاء');

        $parent = ParentService::createParent([
            'full_name_ar'   => trim((string) $request->post('full_name_ar')),
            'full_name_en'   => trim((string) $request->post('full_name_en', '')),
            'phone'          => trim((string) $request->post('phone')),
            'secondary_phone'=> trim((string) $request->post('secondary_phone', '')),
            'email'          => trim((string) $request->post('email', '')),
            'national_id'    => trim((string) $request->post('national_id', '')),
            'relationship'   => $request->post('relationship'),
            'member_id'      => $request->post('member_id') ? (int) $request->post('member_id') : null,
            'is_active'      => 1,
        ]);

        $playerId = $request->post('player_id') ? (int) $request->post('player_id') : null;
        if ($playerId) {
            ParentService::linkPlayer((int) $parent->id, $playerId, $request->post('relationship', 'parent'), true);
        }

        return $this->redirect('/parents')->withSuccess('تم إنشاء حساب ولي الأمر: ' . $request->post('full_name_ar'));
    }

    public function show(Request $request, string $id): Response
    {
        $this->authorize('parent.view');
        $parent = ParentAccount::find((int) $id);
        if (!$parent) return $this->redirect('/parents')->withError('غير موجود');

        $players = $parent->getLinkedPlayers();

        $db = App::getInstance()->db();
        $notifications = $db->select(
            "SELECT * FROM parent_notifications_log WHERE parent_id = ? ORDER BY created_at DESC LIMIT 20",
            [(int) $id]
        );

        return $this->view('ParentPortal.Views.show', [
            'parent'        => $parent,
            'players'       => $players,
            'notifications' => $notifications,
        ]);
    }

    public function linkPlayer(Request $request, string $id): Response
    {
        $this->authorize('parent.manage');
        $playerId = (int) $request->post('player_id', 0);
        if (!$playerId) return $this->redirect("/parents/{$id}")->withError('اختر لاعب');

        ParentService::linkPlayer(
            (int) $id,
            $playerId,
            $request->post('relationship', 'parent'),
            (bool) $request->post('is_primary', 0)
        );

        return $this->redirect("/parents/{$id}")->withSuccess('تم ربط اللاعب');
    }

    public function unlinkPlayer(Request $request, string $id, string $playerId): Response
    {
        $this->authorize('parent.manage');
        ParentService::unlinkPlayer((int) $id, (int) $playerId);
        return $this->redirect("/parents/{$id}")->withSuccess('تم فك الارتباط');
    }

    public function playerDashboard(Request $request, string $id, string $playerId): Response
    {
        $this->authorize('parent.view');
        $data = ParentService::getPlayerDashboard((int) $id, (int) $playerId);
        if (empty($data)) return $this->redirect("/parents/{$id}")->withError('لا يوجد ارتباط بهذا اللاعب');

        return $this->view('ParentPortal.Views.player_dashboard', array_merge($data, [
            'parentId' => (int) $id,
        ]));
    }
}
