<?php
declare(strict_types=1);

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

use Dompdf\Dompdf;
use Dompdf\Options;

class StaffJobcards extends Controller {
    
    private $jobcardModel;

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

        if (isClient()) {
            header('Location: ' . URLROOT . '/clientdashboard/index');
            exit;
        }

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

    public function jobcards(): void {
        $jobcards = $this->jobcardModel->getJobcards('staff', (int)$_SESSION['user_id']);

        $data = [
            'title' => 'My Assigned Jobcards',
            'description' => 'View and manage tasks assigned to you.',
            'jobcards' => $jobcards,
            'help_title' => 'Technician Workflow Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">Technician Workflow</h4>
                <p>This is your operational workspace for resolving client support requests.</p>
                <ul class="list-disc pl-5 space-y-2 mt-2">
                    <li><strong>Start Timer:</strong> When you arrive on-site or begin work, click "Start Job". This stamps the system with the exact start time.</li>
                    <li><strong>Materials:</strong> Log any materials or parts used during the support call. You can add or remove these at any time before completion.</li>
                    <li><strong>Completion:</strong> Detail the work performed and mark the job as completed.</li>
                    <li><strong>Sign-Off:</strong> Once completed, hand the device to the client to sign digitally, then apply your own signature to close the ticket and dispatch the PDF.</li>
                </ul>
            '
        ];

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

    public function history(): void {
        $userId = (int)$_SESSION['user_id'];
        
        // FIX: Utilize the Model method to prevent accessing private database properties
        $jobcards = $this->jobcardModel->getCompletedJobcardsByTechnician($userId);

        $data = [
            'title' => 'My Service History',
            'description' => 'A comprehensive record of your finalized work orders.',
            'jobcards' => $jobcards,
            'help_title' => 'Service History Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">Viewing Past Jobs</h4>
                <p>This matrix stores all jobcards that you have marked as Completed or successfully Signed Off.</p>
                <ul class="list-disc pl-5 space-y-2 mt-2">
                    <li><strong>PDF Downloads:</strong> For any jobcard with a "Signed Off" status, you can download the final PDF copy directly from the matrix.</li>
                </ul>
            '
        ];

        $this->view('staff/jobcards/history', $data);
    }

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

        $jobcard = $this->jobcardModel->getJobcardById((int)$id);
        
        if (!$jobcard || ((int)$jobcard->technician_id !== (int)$_SESSION['user_id'] && !isAdmin() && !isset($_SESSION['admin_impersonating']))) {
            flash('system_msg', 'You do not have permission to view this jobcard.', 'error');
            header('Location: ' . URLROOT . '/staff/jobcards');
            exit;
        }

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

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

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

    public function startTimer($id = null): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && $id) {
            if ($this->jobcardModel->startJobcard((int)$id)) {
                $jobcard = $this->jobcardModel->getJobcardById((int)$id);
                $settings = getSettings();
                
                $notifyBody = "<h2>Jobcard Started: {$jobcard->jobcard_number}</h2>";
                $notifyBody .= "<p>Technician <strong>{$jobcard->tech_name}</strong> has arrived on-site and started work on the jobcard for <strong>{$jobcard->client_name}</strong>.</p>";
                
                sendEmail($jobcard->client_email, "Work Started: {$jobcard->jobcard_number}", $notifyBody);
                
                if (!empty($jobcard->partner_email)) {
                    sendEmail($jobcard->partner_email, "Work Started: {$jobcard->jobcard_number}", $notifyBody);
                } else {
                    $adminEmail = $settings['contact_email'] ?? 'info@christodev.co.za';
                    sendEmail($adminEmail, "Work Started: {$jobcard->jobcard_number}", $notifyBody);
                }

                systemLog('JOBCARD_STARTED', "Technician started jobcard ID {$id}.");
                flash('system_msg', 'Job started. Timer is running. Notifications sent.', 'success');
            }
            header('Location: ' . URLROOT . '/staff/viewJobcard/' . (int)$id);
            exit;
        }
    }

    public function completeJobcard($id = null): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && $id) {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $workDone = trim($_POST['work_done']);

            if (empty($workDone)) {
                flash('system_msg', 'You must detail the work done to complete the jobcard.', 'error');
            } else {
                if ($this->jobcardModel->completeJobcard((int)$id, $workDone)) {
                    $jobcard = $this->jobcardModel->getJobcardById((int)$id);
                    $settings = getSettings();

                    $notifyBody = "<h2>Jobcard Completed: {$jobcard->jobcard_number}</h2>";
                    $notifyBody .= "<p>Technician <strong>{$jobcard->tech_name}</strong> has completed the work for <strong>{$jobcard->client_name}</strong>.</p>";
                    $notifyBody .= "<p>The jobcard is currently awaiting digital signatures to finalize.</p>";
                    $notifyBody .= "<p><strong>Work Performed:</strong><br>" . nl2br(htmlspecialchars($workDone)) . "</p>";

                    sendEmail($jobcard->client_email, "Work Completed: {$jobcard->jobcard_number}", $notifyBody);
                    
                    if (!empty($jobcard->partner_email)) {
                        sendEmail($jobcard->partner_email, "Work Completed: {$jobcard->jobcard_number}", $notifyBody);
                    } else {
                        $adminEmail = $settings['contact_email'] ?? 'info@christodev.co.za';
                        sendEmail($adminEmail, "Work Completed: {$jobcard->jobcard_number}", $notifyBody);
                    }

                    systemLog('JOBCARD_COMPLETED', "Technician completed jobcard ID {$id}. Waiting for signatures.");
                    flash('system_msg', 'Job marked as completed. Please proceed to signatures. Notifications sent.', 'success');
                }
            }
            header('Location: ' . URLROOT . '/staff/viewJobcard/' . (int)$id);
            exit;
        }
    }

    public function addMaterial(): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

            $data = [
                'jobcard_id' => (int)$_POST['jobcard_id'],
                'material_name' => trim($_POST['material_name']),
                'quantity' => trim($_POST['quantity'])
            ];

            if (!empty($data['material_name']) && !empty($data['quantity'])) {
                $this->jobcardModel->addMaterial($data);
                flash('system_msg', 'Material added successfully.', 'success');
            } else {
                flash('system_msg', 'Material name and quantity are required.', 'error');
            }

            header('Location: ' . URLROOT . '/staff/viewJobcard/' . $data['jobcard_id']);
            exit;
        }
    }

    public function deleteMaterial($id = null, $jobcardId = null): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && $id && $jobcardId) {
            $this->jobcardModel->deleteMaterial((int)$id);
            flash('system_msg', 'Material removed.', 'success');
            header('Location: ' . URLROOT . '/staff/viewJobcard/' . (int)$jobcardId);
            exit;
        }
    }

    public function signoff($id = null): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && $id) {
            $clientSig = $_POST['client_signature'] ?? '';
            $techSig = $_POST['tech_signature'] ?? '';
            $clientSignName = trim($_POST['client_sign_name'] ?? '');
            $techSignName = trim($_POST['tech_sign_name'] ?? '');

            if (empty($clientSig) || empty($techSig) || empty($clientSignName) || empty($techSignName)) {
                flash('system_msg', 'Both signatures and printed names are required.', 'error');
                header('Location: ' . URLROOT . '/staff/viewJobcard/' . (int)$id);
                exit;
            }

            if ($this->jobcardModel->signOffJobcard((int)$id, $clientSig, $techSig, $clientSignName, $techSignName)) {
                
                $jobcard = $this->jobcardModel->getJobcardById((int)$id);
                $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();

                    $pdfOutput = $dompdf->output();

                    $tempDir = dirname(__DIR__, 2) . '/public/uploads/temp_support/';
                    if (!is_dir($tempDir)) { mkdir($tempDir, 0755, true); }
                    
                    $pdfFileName = 'Jobcard_' . $jobcard->jobcard_number . '.pdf';
                    $pdfFilePath = $tempDir . $pdfFileName;
                    file_put_contents($pdfFilePath, $pdfOutput);

                    $appName = $settings['app_name'] ?? SITENAME;
                    $body = "<h2 style='color:#1f2937; margin-top:0;'>Jobcard Finalized: {$jobcard->jobcard_number}</h2>";
                    $body .= "<p>Hello,</p>";
                    $body .= "<p>The technical support jobcard <strong>{$jobcard->jobcard_number}</strong> has been successfully signed off and finalized by the technician on site.</p>";
                    $body .= "<p>A comprehensive PDF copy detailing the work performed, materials used, and digital signatures is attached to this email for your records.</p>";
                    
                    $recipients = [$jobcard->client_email, $jobcard->tech_email];
                    if (!empty($jobcard->partner_email)) {
                        $recipients[] = $jobcard->partner_email;
                    } else {
                        $adminEmail = $settings['contact_email'] ?? 'info@christodev.co.za';
                        $recipients[] = $adminEmail;
                    }

                    sendEmail($recipients, "Completed Jobcard: {$jobcard->jobcard_number}", $body, [$pdfFilePath]);

                } else {
                    error_log("Dompdf class not found. PDF not generated.");
                }

                systemLog('JOBCARD_SIGNED_OFF', "Jobcard ID {$id} was signed and finalized. PDF queued for dispatch.");
                flash('system_msg', 'Jobcard finalized and signed successfully. PDF dispatched.', 'success');
                header('Location: ' . URLROOT . '/staff/jobcards');
                exit;
            }
        }
    }

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

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

        if (!$jobcard || $jobcard->status !== 'Signed Off' || ((int)$jobcard->technician_id !== (int)$_SESSION['user_id'] && !isAdmin() && !isset($_SESSION['admin_impersonating']))) {
            flash('system_msg', 'Jobcard not found or permission denied.', 'error');
            header('Location: ' . URLROOT . '/staff/jobcards');
            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', "Technician 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 . '/staff/viewJobcard/' . $id);
            exit;
        }
    }
}