<?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\AdvanceSalary;
use App\Models\Notification;
use App\Models\User;
use PDO;

class AdvanceController 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']);

        $this->view('advance/create', [
            'csrf' => Csrf::field(),
            'message' => SessionHelper::flash('message'),
            'error' => SessionHelper::flash('error'),
            'user' => SessionHelper::user(),
        ]);
    }

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

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

        $user = SessionHelper::user();

        $data = [
            'nama' => $user['name'],
            'jumlah' => filter_var($_POST['jumlah'] ?? 0, FILTER_VALIDATE_FLOAT),
            'tujuan' => trim($_POST['tujuan'] ?? ''),
            'kenyataan_setuju' => isset($_POST['kenyataan_setuju']) ? 1 : 0,
        ];

        if (!$data['jumlah'] || $data['jumlah'] <= 0 || !$data['tujuan'] || !$data['kenyataan_setuju']) {
            SessionHelper::flash('error', 'Please complete the form correctly.');
            header('Location: index.php?route=advance/create');
            exit;
        }

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

        $notificationModel = new Notification($this->pdo);
        $approver = (new User($this->pdo))->findByLoginId($this->approverLoginId);

        if ($approver) {
            $notificationModel->create([
                'user_id' => $approver['id'],
                'type' => 'advance',
                'message' => "Advance Salary request #{$id} pending approval",
            ]);

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

        SessionHelper::flash('message', 'Advance salary submitted.');
        header('Location: index.php?route=advance/create');
    }

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

