<?php
declare(strict_types=1);

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

use Dompdf\Dompdf;
use Dompdf\Options;

class PartnerDashboard extends Controller {
    
    private $jobcardModel;

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

        // Allow access if they are a Partner OR if an Admin is impersonating a partner
        if (!isPartner() && !isset($_SESSION['admin_impersonating'])) {
            header('Location: ' . URLROOT . '/dashboard/index');
            exit;
        }

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

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

        // A partner user tracks jobcards by the partner_id linked to their account
        $jobcards = $this->jobcardModel->getJobcards('partner', (int)$user->partner_id);

        $data = [
            'title' => 'Agency Portal',
            'description' => 'Welcome to your dedicated agency workspace.',
            'user' => $user,
            'jobcards' => $jobcards,
            
            // Contextual Help
            'help_title' => 'Agency Portal Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">Agency Workspace</h4>
                <p>Welcome to your agency portal. You can track all service requests initiated for your clients here.</p>
                <ul class="list-disc pl-5 space-y-2 mt-2">
                    <li><strong>Service History:</strong> Track the real-time status of all active and completed technical support requests for your clients.</li>
                    <li><strong>PDF Downloads:</strong> Once a job is marked "Signed Off", a download button will appear allowing you to securely save the co-branded PDF document.</li>
                </ul>
            '
        ];

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

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

        $jobcard = $this->jobcardModel->getJobcardById((int)$id);
        $userModel = $this->model('User');
        $user = $userModel->getUserById((int)$_SESSION['user_id']);

        // Security: Ensure the partner owns this jobcard
        if (!$jobcard || ((int)$jobcard->partner_id !== (int)$user->partner_id && !isset($_SESSION['admin_impersonating']))) {
            flash('system_msg', 'Jobcard not found or permission denied.', 'error');
            header('Location: ' . URLROOT . '/partnerDashboard/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('partner/view', $data);
    }

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

        $jobcard = $this->jobcardModel->getJobcardById((int)$id);
        $userModel = $this->model('User');
        $user = $userModel->getUserById((int)$_SESSION['user_id']);
        
        // Ensure the partner owns this jobcard
        if (!$jobcard || $jobcard->status !== 'Signed Off' || ((int)$jobcard->partner_id !== (int)$user->partner_id && !isset($_SESSION['admin_impersonating']))) {
            flash('system_msg', 'Jobcard not found or permission denied.', 'error');
            header('Location: ' . URLROOT . '/partnerDashboard/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', "Partner 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 . '/partnerDashboard/index');
            exit;
        }
    }
}