<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Helpers\Csrf;
use App\Helpers\Mailer;
use App\Helpers\SessionHelper;
use App\Models\LeaveRequest;
use App\Models\StaffProfile;
use App\Models\Notification;
use App\Models\User;
use PDO;

class LeaveController extends Controller
{
    private string $approverLoginId = '888888888888';

    private PDO $pdo;  // Declare property manually

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo; // Assign manually (PHP 7.4 style)
    }

    public function create(): void
    {
        Auth::requireRole(['staff']);

        $user = SessionHelper::user();
        $profile = (new StaffProfile($this->pdo))->findByUserId($user['id']);
        $this->view('leave/create', [
            'csrf' => Csrf::field(),
            'message' => SessionHelper::flash('message'),
            'error' => SessionHelper::flash('error'),
            'user' => $user,
            'location' => $profile['location'] ?? '',
        ]);
    }

    public function store(): void
    {
        Auth::requireRole(['staff']);

        if (!Csrf::validate($_POST['_token'] ?? null)) {
            SessionHelper::flash('error', 'Invalid CSRF token');
            header('Location: index.php?route=leave/create');
            exit;
        }

        $tarikhMula = $_POST['tarikh_mula'] ?? '';
        $tarikhAkhir = $_POST['tarikh_akhir'] ?? '';
        $jumlahHari = $this->calculateDays($tarikhMula, $tarikhAkhir);

        $user = SessionHelper::user();
        $profile = (new StaffProfile($this->pdo))->findByUserId($user['id']) ?? [];
        $location = trim($profile['location'] ?? '');
        if ($location === '') {
            SessionHelper::flash('error', 'Lokasi pekerja tidak ditemui. Sila hubungi pentadbir.');
            header('Location: index.php?route=leave/create');
            exit;
        }

        $data = [
            'nama' => $user['name'],
            'tempat_bekerja' => $location,
            'alasan' => trim($_POST['alasan'] ?? ''),
            'tarikh_mula' => $tarikhMula,
            'tarikh_akhir' => $tarikhAkhir,
            'jumlah_hari' => $jumlahHari,
            'kenyataan' => $_POST['kenyataan'] ?? '',
        ];

        if (!$data['nama'] || !$data['tempat_bekerja'] || !$data['alasan'] || !$jumlahHari) {
            SessionHelper::flash('error', 'Please complete the form correctly.');
            header('Location: index.php?route=leave/create');
            exit;
        }

        $model = new LeaveRequest($this->pdo);
        $data['user_id'] = $user['id'];
        $id = $model->create($data);

        $approver = (new User($this->pdo))->findByLoginId($this->approverLoginId);
        if ($approver) {
            (new Notification($this->pdo))->create([
                'user_id' => $approver['id'],
                'type' => 'leave',
                'message' => "Leave request #{$id} pending approval",
            ]);

            if (!empty($approver['email'])) {
                Mailer::send(
                    $approver['email'],
                    'Leave Request Pending Approval',
                    $this->renderEmail('emails/pending.php', [
                        'subject' => 'Leave Request Pending Approval',
                        'message' => "Please review leave request #{$id}.",
                    ])
                );
            }
        }

        SessionHelper::flash('message', 'Leave request submitted.');
        header('Location: index.php?route=leave/create');
    }

    private function calculateDays(string $start, string $end): int
    {
        try {
            $startDate = new \DateTimeImmutable($start);
            $endDate = new \DateTimeImmutable($end);
            if ($endDate < $startDate) {
                return 0;
            }
            return $startDate->diff($endDate)->days + 1;
        } catch (\Exception $e) {
            return 0;
        }
    }

    private function renderEmail(string $template, array $data): string
    {
        ob_start();
        extract($data);
        include __DIR__ . '/../views/' . $template;
        return (string) ob_get_clean();
    }
}

