<?php
require_once __DIR__ . '/../models/CustomerPortalUser.php';

class PortalController extends Controller
{
    public function login(): void
    {
        if (PortalAuth::check()) {
            $this->redirect('/portal/dashboard');
        }

        $this->view('portal.login', ['title' => 'Customer Portal Login | Balorp Ventures']);
    }

    public function authenticate(): void
    {
        if (!$this->isPost()) {
            $this->redirect('/portal/login');
        }

        $token = $_POST['csrf_token'] ?? '';
        if (!CSRF::validate($token)) {
            $this->setFlash('error', 'Invalid CSRF token.');
            $this->redirect('/portal/login');
        }

        $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
        $password = $_POST['password'] ?? '';

        if (!$email || !$password) {
            $this->view('portal.login', ['title' => 'Customer Portal Login | Balorp Ventures', 'error' => 'Enter a valid email and password.']);
            return;
        }

        $portalUser = new CustomerPortalUser();
        $user = $portalUser->findByEmail($email);

        if ($user && password_verify($password, $user['password_hash'])) {
            PortalAuth::login($user);
            $this->redirect('/portal/dashboard');
        }

        $this->view('portal.login', ['title' => 'Customer Portal Login | Balorp Ventures', 'error' => 'Invalid credentials.']);
    }

    public function dashboard(): void
    {
        PortalAuth::guard();

        $portalUser = new CustomerPortalUser();
        $user = PortalAuth::user();
        $customerId = (int)($user['customer_id'] ?? 0);

        $quotations = $portalUser->getQuotations($customerId);
        $projects = $portalUser->getProjects($customerId);
        $invoices = $portalUser->getInvoices($customerId);
        $documents = $portalUser->getDocuments($customerId);
        $projectPhotos = $portalUser->getProjectPhotos($customerId);

        $this->view('portal.dashboard', [
            'title' => 'Customer Portal | Balorp Ventures',
            'user' => $user,
            'quotations' => $quotations,
            'projects' => $projects,
            'invoices' => $invoices,
            'documents' => $documents,
            'projectPhotos' => $projectPhotos,
        ]);
    }

    public function invoice(): void
    {
        PortalAuth::guard();

        $invoiceId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
        if (!$invoiceId) {
            $this->redirect('/portal/dashboard');
        }

        $portalUser = new CustomerPortalUser();
        $user = PortalAuth::user();
        $customerId = (int)($user['customer_id'] ?? 0);

        $invoice = $portalUser->getInvoiceById($invoiceId, $customerId);
        if (!$invoice) {
            $this->redirect('/portal/dashboard');
        }

        $items = $portalUser->getInvoiceItems($invoiceId);
        $invoiceDocument = $portalUser->findInvoiceDocument($invoiceId, $customerId);

        $this->view('portal.invoice', [
            'title' => 'Invoice Details | Balorp Ventures',
            'user' => $user,
            'invoice' => $invoice,
            'items' => $items,
            'invoiceDocument' => $invoiceDocument,
        ]);
    }

    public function gallery(): void
    {
        PortalAuth::guard();

        $portalUser = new CustomerPortalUser();
        $user = PortalAuth::user();
        $customerId = (int)($user['customer_id'] ?? 0);

        $projectId = filter_input(INPUT_GET, 'project_id', FILTER_VALIDATE_INT);
        $photos = $portalUser->getProjectPhotos($customerId, $projectId);

        $this->view('portal.gallery', [
            'title' => 'Project Gallery | Balorp Ventures',
            'user' => $user,
            'photos' => $photos,
            'projectId' => $projectId,
        ]);
    }

    public function downloadDocument(): void
    {
        PortalAuth::guard();

        $documentId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
        if (!$documentId) {
            $this->redirect('/portal/dashboard');
        }

        $portalUser = new CustomerPortalUser();
        $user = PortalAuth::user();
        $customerId = (int)($user['customer_id'] ?? 0);

        $document = $portalUser->findDocumentById($documentId, $customerId);
        if (!$document) {
            $this->redirect('/portal/dashboard');
        }

        $absolutePath = file_exists($filePath) ? $filePath : __DIR__ . '/../../' . ltrim($filePath, '/');
        if (!file_exists($absolutePath)) {
            $this->setFlash('error', 'Document file not found.');
            $this->redirect('/portal/dashboard');
        }

        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($absolutePath) . '"');
        header('Content-Length: ' . filesize($absolutePath));
        readfile($absolutePath);
        exit;
    }

    public function logout(): void
    {
        PortalAuth::logout();
        $this->redirect('/portal/login');
    }
}
