<?php
declare(strict_types=1);

// Christo Lochenberg Developments | info@christodev.co.za | +27 61 523 9126

use Dompdf\Dompdf;
use Dompdf\Options;

class ClientDashboard extends Controller {
    
    private $jobcardModel;

    public function __construct() {
        if (!isLoggedIn()) {
            header('Location: ' . URLROOT . '/users/login');
            exit;
        }

        $this->jobcardModel = $this->model('Jobcard');
    }

    public function index(): void {
        $userModel = $this->model('User');
        $user = $userModel->getUserById((int)$_SESSION['user_id']);

        $jobcards = $this->jobcardModel->getJobcards('client', (int)$_SESSION['user_id']);

        $data = [
            'title' => 'Client Portal',
            'description' => 'Welcome to your dedicated client workspace.',
            'user' => $user,
            'jobcards' => $jobcards,
            
            // Contextual Help
            'help_title' => 'Client Portal Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">Client Workspace</h4>
                <p>Welcome to your personal client portal. This is where you can view your details and track your service history.</p>
                <ul class="list-disc pl-5 space-y-2 mt-2">
                    <li><strong>Service History:</strong> Track the status of active technical support requests and review completed jobs.</li>
                    <li><strong>PDF Downloads:</strong> Once a job is marked "Signed Off", a download button will appear allowing you to securely save the finalized PDF document.</li>
                </ul>
            '
        ];

        $this->view('client/index', $data);
    }

    public function viewJobcard($id = null): void {
        if (!$id) {
            header('Location: ' . URLROOT . '/clientdashboard/index');
            exit;
        }

        $jobcard = $this->jobcardModel->getJobcardById((int)$id);

        if (!$jobcard || ((int)$jobcard->client_id !== (int)$_SESSION['user_id'] && !isset($_SESSION['admin_impersonating']))) {
            flash('system_msg', 'Jobcard not found or permission denied.', 'error');
            header('Location: ' . URLROOT . '/clientdashboard/index');
            exit;
        }

        $materials = $this->jobcardModel->getMaterialsByJobcard((int)$id);
        $settings = getSettings();

        $data = [
            'title' => 'View Jobcard: ' . $jobcard->jobcard_number,
            'jobcard' => $jobcard,
            'materials' => $materials,
            'settings' => $settings
        ];

        $this->view('client/view', $data);
    }

    public function downloadPdf($id = null): void {
        if (!$id) {
            header('Location: ' . URLROOT . '/clientdashboard/index');
            exit;
        }

        $jobcard = $this->jobcardModel->getJobcardById((int)$id);
        
        if (!$jobcard || $jobcard->status !== 'Signed Off' || ((int)$jobcard->client_id !== (int)$_SESSION['user_id'] && !isset($_SESSION['admin_impersonating']))) {
            flash('system_msg', 'Jobcard not found or permission denied.', 'error');
            header('Location: ' . URLROOT . '/clientdashboard/index');
            exit;
        }

        $materials = $this->jobcardModel->getMaterialsByJobcard((int)$id);
        $settings = getSettings();

        if (class_exists('Dompdf\Dompdf')) {
            $options = new Options();
            $options->set('isHtml5ParserEnabled', true);
            $options->set('isRemoteEnabled', true);
            $options->set('defaultFont', 'Helvetica');
            
            $dompdf = new Dompdf($options);

            ob_start();
            $data = ['jobcard' => $jobcard, 'materials' => $materials, 'settings' => $settings];
            require APPROOT . '/app/Views/staff/jobcards/pdf.php';
            $html = ob_get_clean();

            $dompdf->loadHtml($html);
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();

            systemLog('JOBCARD_PDF_DOWNLOADED', "Client downloaded PDF for Jobcard: {$jobcard->jobcard_number}");

            $dompdf->stream('Jobcard_' . $jobcard->jobcard_number . '.pdf', ['Attachment' => true]);
            exit;
        } else {
            flash('system_msg', 'PDF Generation engine not found.', 'error');
            header('Location: ' . URLROOT . '/clientdashboard/index');
            exit;
        }
    }
}