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

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

    private PDO $pdo;

	public function __construct(PDO $pdo)
	{
		$this->pdo = $pdo;

		$this->uploadDir = __DIR__ . '/../../public/uploads/claims';
		if (!is_dir($this->uploadDir)) {
			mkdir($this->uploadDir, 0775, true);
		}
	}

    public function create(): void
    {
        Auth::requireRole(['staff']);
        $user = SessionHelper::user();
        $profile = (new StaffProfile($this->pdo))->findByUserId($user['id']) ?? [];
        $this->view('claim/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=claim/create');
            exit;
        }

        if (!isset($_FILES['invoice']) || $_FILES['invoice']['error'] !== UPLOAD_ERR_OK) {
            SessionHelper::flash('error', 'Please upload invoice file.');
            header('Location: index.php?route=claim/create');
            exit;
        }

        $allowed = ['pdf', 'jpg', 'jpeg', 'png'];
        $ext = strtolower(pathinfo($_FILES['invoice']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed, true)) {
            SessionHelper::flash('error', 'Invalid file type.');
            header('Location: index.php?route=claim/create');
            exit;
        }

        $filename = uniqid('claim_') . '.' . $ext;
        $target = $this->uploadDir . '/' . $filename;
        if (!move_uploaded_file($_FILES['invoice']['tmp_name'], $target)) {
            SessionHelper::flash('error', 'Unable to store file.');
            header('Location: index.php?route=claim/create');
            exit;
        }

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

        $data = [
            'jabatan' => $location,
            'tujuan' => trim($_POST['tujuan'] ?? ''),
            'amount' => filter_var($_POST['amount'] ?? 0, FILTER_VALIDATE_FLOAT),
            'catatan' => trim($_POST['catatan'] ?? ''),
            'file_path' => $filename,
        ];

        $data['nama_staff'] = $user['name'];

        if (!$data['jabatan'] || !$data['tujuan'] || !$data['amount']) {
            unlink($target);
            SessionHelper::flash('error', 'Please complete the form correctly.');
            header('Location: index.php?route=claim/create');
            exit;
        }

        $model = new Claim($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' => 'claim',
                'message' => "Claim #{$id} pending approval",
            ]);

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

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

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

