<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

class AcademyContractController extends Controller
{
    /**
     * List contracts for an academy.
     */
    public function index(Request $request, string $aid): Response
    {
        $db = App::getInstance()->db();

        $academy = $db->selectOne("SELECT * FROM sa_academies WHERE id = ?", [(int) $aid]);
        if (!$academy) {
            return $this->redirect('/sa/academies')->withError('الأكاديمية غير موجودة');
        }

        $contracts = $db->select(
            "SELECT * FROM sa_academy_contracts WHERE academy_id = ? ORDER BY created_at DESC",
            [(int) $aid]
        );

        return $this->view('SportsActivity.Views.academies.contracts', [
            'academy'   => $academy,
            'contracts' => $contracts,
        ]);
    }

    /**
     * Show create contract form for an academy.
     */
    public function create(Request $request, string $aid): Response
    {
        $db = App::getInstance()->db();

        $academy = $db->selectOne("SELECT * FROM sa_academies WHERE id = ?", [(int) $aid]);
        if (!$academy) {
            return $this->redirect('/sa/academies')->withError('الأكاديمية غير موجودة');
        }

        return $this->view('SportsActivity.Views.academies.contract_form', [
            'academy'  => $academy,
            'contract' => null,
        ]);
    }

    /**
     * Validate and store a new contract.
     */
    public function store(Request $request, string $aid): Response
    {
        $db = App::getInstance()->db();
        $session = App::getInstance()->session();

        $academy = $db->selectOne("SELECT * FROM sa_academies WHERE id = ?", [(int) $aid]);
        if (!$academy) {
            return $this->redirect('/sa/academies')->withError('الأكاديمية غير موجودة');
        }

        $contractNumber = trim((string) $request->post('contract_number', ''));
        $contractType = trim((string) $request->post('contract_type', 'revenue_share'));
        $startDate = trim((string) $request->post('start_date', ''));
        $endDate = trim((string) $request->post('end_date', ''));
        $clubCommissionPct = (float) $request->post('club_commission_pct', 0);
        $academySharePct = (float) $request->post('academy_share_pct', 0);
        $fixedMonthlyRent = (float) $request->post('fixed_monthly_rent', 0);
        $depositAmount = (float) $request->post('deposit_amount', 0);
        $notes = trim((string) $request->post('notes', ''));

        // Validation
        $errors = [];
        if ($contractNumber === '') {
            $errors[] = 'رقم العقد مطلوب';
        } elseif (mb_strlen($contractNumber) > 50) {
            $errors[] = 'رقم العقد يجب ألا يتجاوز 50 حرف';
        }
        $validContractTypes = ['revenue_share', 'fixed_rent', 'hybrid'];
        if ($contractType === '' || !in_array($contractType, $validContractTypes)) {
            $errors[] = 'نوع العقد مطلوب';
        }
        if ($startDate === '') {
            $errors[] = 'تاريخ البداية مطلوب';
        }
        if ($endDate === '') {
            $errors[] = 'تاريخ النهاية مطلوب';
        }
        if ($startDate !== '' && $endDate !== '' && $startDate >= $endDate) {
            $errors[] = 'تاريخ البداية يجب أن يكون قبل تاريخ النهاية';
        }
        if ($clubCommissionPct < 0 || $clubCommissionPct > 100) {
            $errors[] = 'نسبة النادي يجب أن تكون بين 0 و 100';
        }
        if ($academySharePct < 0 || $academySharePct > 100) {
            $errors[] = 'نسبة الأكاديمية يجب أن تكون بين 0 و 100';
        }
        if ($fixedMonthlyRent < 0) {
            $errors[] = 'الإيجار الشهري لا يمكن أن يكون سالب';
        }
        if ($depositAmount < 0) {
            $errors[] = 'مبلغ التأمين لا يمكن أن يكون سالب';
        }

        // Duplicate contract number check
        if ($contractNumber !== '') {
            $existingContract = $db->selectOne(
                "SELECT id FROM sa_academy_contracts WHERE contract_number = ?",
                [$contractNumber]
            );
            if ($existingContract) {
                $errors[] = 'رقم العقد مستخدم بالفعل';
            }
        }

        // File upload validation
        $file = $_FILES['contract_pdf'] ?? null;
        if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = 'ملف العقد (PDF) مطلوب';
        } elseif ($file && $file['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            if ($ext !== 'pdf') {
                $errors[] = 'ملف العقد يجب أن يكون بصيغة PDF فقط';
            }
        }

        if (!empty($errors)) {
            $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
            $session->flash('_old_input', $request->all());
            return $this->redirect('/sa/academies/' . $aid . '/contracts/create');
        }

        // Upload PDF
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $newName = uniqid('contract_') . '.' . $ext;
        $uploadDir = dirname(__DIR__, 4) . '/public/uploads/sa_contracts/';

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $dest = $uploadDir . $newName;
        move_uploaded_file($file['tmp_name'], $dest);

        $pdfPath = 'uploads/sa_contracts/' . $newName;

        $data = [
            'academy_id'          => (int) $aid,
            'contract_number'     => $contractNumber,
            'contract_type'       => $contractType,
            'start_date'          => $startDate,
            'end_date'            => $endDate,
            'club_commission_pct' => $clubCommissionPct,
            'academy_share_pct'   => $academySharePct,
            'fixed_monthly_rent'  => $fixedMonthlyRent,
            'deposit_amount'      => $depositAmount,
            'contract_pdf_path'   => $pdfPath,
            'status'              => 'pending_approval',
            'notes'               => $notes ?: null,
            'created_by'          => (int) ($session->get('employee_id') ?? 0),
            'created_at'          => now(),
            'updated_at'          => now(),
        ];

        $db->insert('sa_academy_contracts', $data);
        $contractId = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id")['id'];

        return $this->redirect('/sa/academy-contracts/' . $contractId)->withSuccess('تم إضافة العقد بنجاح');
    }

    /**
     * Show contract detail.
     */
    public function show(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();

        $contract = $db->selectOne(
            "SELECT c.*, a.name_ar as academy_name, a.code as academy_code
             FROM sa_academy_contracts c
             LEFT JOIN sa_academies a ON a.id = c.academy_id
             WHERE c.id = ?",
            [(int) $id]
        );

        if (!$contract) {
            return $this->redirect('/sa/academies')->withError('العقد غير موجود');
        }

        return $this->view('SportsActivity.Views.academies.contract_show', [
            'contract' => $contract,
        ]);
    }

    /**
     * Approve a contract — set status='active', record approved_by and approved_at.
     */
    public function approve(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $session = App::getInstance()->session();

        $contract = $db->selectOne("SELECT * FROM sa_academy_contracts WHERE id = ?", [(int) $id]);
        if (!$contract) {
            return $this->redirect('/sa/academies')->withError('العقد غير موجود');
        }

        if ($contract['status'] !== 'pending_approval') {
            return $this->redirect('/sa/academy-contracts/' . $id)->withError('لا يمكن اعتماد هذا العقد - الحالة الحالية لا تسمح بذلك');
        }

        $db->update('sa_academy_contracts', [
            'status'      => 'active',
            'approved_by' => (int) ($session->get('employee_id') ?? 0),
            'approved_at' => now(),
            'updated_at'  => now(),
        ], 'id = ?', [(int) $id]);

        return $this->redirect('/sa/academy-contracts/' . $id)->withSuccess('تم اعتماد العقد بنجاح');
    }
}
