<?php
declare(strict_types=1);

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

class Support extends Controller {
    
    private $supportModel;

    public function __construct() {
        // Strict Security Gate: Must be logged in to log a support ticket!
        if (!isLoggedIn()) {
            header('Location: ' . URLROOT . '/users/login');
            exit;
        }
        $this->supportModel = $this->model('SupportModel');
    }

    public function index(): void {
        // Fetch the user's past tickets
        $tickets = $this->supportModel->getTicketsByUser((int)$_SESSION['user_id']);

        $data = [
            'title' => 'Developer Support',
            'description' => 'Report a bug or request a feature directly to the development team.',
            'tickets' => $tickets,
            
            // Contextual Help
            'help_title' => 'Support Desk Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">How Support Works</h4>
                <p>Fill out the form to securely send a diagnostic request directly to our engineering team.</p>
                <ul class="list-disc pl-5 space-y-2 mt-2">
                    <li><strong>Tracking:</strong> Once submitted, a unique Ticket ID is assigned so you can track its progress below.</li>
                    <li><strong>Resolution:</strong> When your issue is fixed via an OTA update or your question is answered, you can click the green checkmark to mark the ticket as "Resolved" to close it out.</li>
                </ul>
            '
        ];
        
        $this->view('support/index', $data);
    }

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

            $ticketType = trim($_POST['ticket_type'] ?? 'Report a Bug');
            $subject = trim($_POST['subject'] ?? '');
            $description = trim($_POST['description'] ?? '');
            
            if (empty($subject) || empty($description)) {
                flash('system_msg', 'Subject and Description are required to submit a ticket.', 'error');
                header('Location: ' . URLROOT . '/support/index');
                exit;
            }

            // Handle User File Uploads & Pasted Images
            $attachmentPaths = [];
            $tempDir = dirname(__DIR__, 2) . '/public/uploads/temp_support/';
            
            if (!is_dir($tempDir)) {
                mkdir($tempDir, 0755, true);
            }

            if (!empty($_FILES['attachments']['name'][0])) {
                $fileCount = count($_FILES['attachments']['name']);
                for ($i = 0; $i < $fileCount; $i++) {
                    if ($_FILES['attachments']['error'][$i] === 0) {
                        $tmpName = $_FILES['attachments']['tmp_name'][$i];
                        $originalName = basename($_FILES['attachments']['name'][$i]);
                        $safeFileName = preg_replace("/[^a-zA-Z0-9\._-]/", "", $originalName);
                        $fileName = time() . '_' . $i . '_' . $safeFileName;
                        
                        $destPath = $tempDir . $fileName;
                        if (move_uploaded_file($tmpName, $destPath)) {
                            $attachmentPaths[] = $destPath;
                        }
                    }
                }
            }

            // =========================================================
            // AUTO-ATTACH SYSTEM ERROR LOG
            // =========================================================
            $errorLogPath = dirname(__DIR__, 2) . '/logs/error.log';
            if (file_exists($errorLogPath)) {
                $attachmentPaths[] = $errorLogPath; // Silently attach the system log
            }

            // Generate a random ticket number
            $ticketNumber = 'TKT-' . rand(100000, 999999);

            // Save clean data to Database for the User's view
            $ticketData = [
                'user_id' => $_SESSION['user_id'],
                'ticket_number' => $ticketNumber,
                'ticket_type' => $ticketType,
                'subject' => $subject,
                'description' => $description
            ];

            if ($this->supportModel->createTicket($ticketData)) {
                
                // =========================================================
                // GATHER SYSTEM DIAGNOSTICS FOR DEVELOPER EMAIL
                // =========================================================
                $settings = getSettings();
                $appVersion = file_exists(APPROOT . '/version.php') ? include APPROOT . '/version.php' : 'Unknown';
                $phpVersion = phpversion();
                $serverSoft = $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown';
                
                // Get MySQL Version
                $db = new Database();
                $db->query("SELECT VERSION() as version");
                $mysqlVersion = $db->single()->version ?? 'Unknown';

                // Check critical directories
                $logDir = dirname(__DIR__, 2) . '/logs';
                $uploadDir = dirname(__DIR__, 2) . '/public/uploads';
                $logWritable = is_writable($logDir) ? '<span style="color:#16a34a;">Writable</span>' : '<span style="color:#dc2626;">Read-Only</span>';
                $uploadWritable = is_writable($uploadDir) ? '<span style="color:#16a34a;">Writable</span>' : '<span style="color:#dc2626;">Read-Only</span>';

                // Check PHP Extensions
                $exts = ['pdo', 'pdo_mysql', 'mbstring', 'curl', 'openssl', 'json', 'zip', 'gd', 'xml'];
                $extStatusHtml = "";
                foreach($exts as $ext) {
                    $status = extension_loaded($ext) ? 'Enabled' : 'Disabled';
                    $color = $status === 'Enabled' ? '#16a34a' : '#dc2626';
                    $extStatusHtml .= "<strong>{$ext}:</strong> <span style='color: {$color};'>{$status}</span> | ";
                }

                $licenseKey = $settings['license_key'] ?? 'Not Set';
                $appName = $settings['app_name'] ?? SITENAME;
                $appUrl = URLROOT;

                // =========================================================
                // CONSTRUCT THE EMAIL BODY
                // =========================================================
                $userName = $_SESSION['user_name'];
                $userEmail = $_SESSION['user_email'];
                
                $body = "<h2 style='color:#1f2937; margin-top:0;'>New Developer Support Request</h2>";
                $body .= "<p><strong>Ticket ID:</strong> {$ticketNumber}</p>";
                $body .= "<p><strong>From:</strong> {$userName} ({$userEmail})</p>";
                $body .= "<p><strong>Ticket Type:</strong> {$ticketType}</p>";
                $body .= "<p><strong>Subject:</strong> {$subject}</p>";
                $body .= "<hr style='border:none; border-top:1px solid #e5e7eb; margin: 20px 0;'>";
                $body .= "<p><strong>User Description:</strong></p>";
                $body .= "<p style='white-space: pre-wrap; font-family: monospace; background: #f9fafb; padding: 15px; border-radius: 5px; border: 1px solid #e5e7eb;'>" . htmlspecialchars($description) . "</p>";

                // Inject the Diagnostics Block
                $body .= "
                <br>
                <hr style='border:none; border-top:2px dashed #e5e7eb; margin: 30px 0;'>
                <h3 style='color:#1f2937; margin-bottom: 10px;'>Automated System Diagnostics</h3>
                <table style='width: 100%; border-collapse: collapse; font-size: 13px; color: #374151; font-family: sans-serif;'>
                    <tr><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6; width: 150px;'><strong>App Name:</strong></td><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'>{$appName}</td></tr>
                    <tr><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'><strong>Live URL:</strong></td><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'><a href='{$appUrl}'>{$appUrl}</a></td></tr>
                    <tr><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'><strong>License Key:</strong></td><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6; font-family: monospace;'>{$licenseKey}</td></tr>
                    <tr><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'><strong>App Version:</strong></td><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'>v{$appVersion}</td></tr>
                    <tr><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'><strong>DB Version:</strong></td><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'>v" . ($settings['db_version'] ?? 'N/A') . "</td></tr>
                    <tr><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'><strong>PHP Version:</strong></td><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'>{$phpVersion}</td></tr>
                    <tr><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'><strong>MySQL Version:</strong></td><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'>{$mysqlVersion}</td></tr>
                    <tr><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'><strong>Server Software:</strong></td><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'>{$serverSoft}</td></tr>
                    <tr><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'><strong>/logs Directory:</strong></td><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'>{$logWritable}</td></tr>
                    <tr><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'><strong>/uploads Directory:</strong></td><td style='padding: 6px 0; border-bottom: 1px solid #f3f4f6;'>{$uploadWritable}</td></tr>
                </table>
                <h4 style='color:#1f2937; margin-top: 20px; margin-bottom: 8px; font-family: sans-serif;'>PHP Extensions Status:</h4>
                <p style='font-size: 12px; color: #4b5563; margin-top: 0; line-height: 1.6;'>
                    {$extStatusHtml}
                </p>";

                $to = 'support@christodev.co.za'; 
                $emailSubject = "Support: [#{$ticketNumber}] [" . $ticketType . "] " . $subject;

                // Queue the email
                if (sendEmail($to, $emailSubject, $body, $attachmentPaths)) {
                    systemLog('SUPPORT_TICKET_SUBMITTED', "User submitted ticket {$ticketNumber}. Diagnostics & Error Log auto-attached.");
                    flash('system_msg', "Your ticket (#{$ticketNumber}) has been submitted successfully! The team will be in touch.", 'success');
                } else {
                    flash('system_msg', 'Your ticket was saved, but there was an error queuing the email notification.', 'error');
                }
            } else {
                flash('system_msg', 'A database error occurred while creating your ticket. Please try again.', 'error');
            }

            header('Location: ' . URLROOT . '/support/index');
            exit;
            
        } else {
            header('Location: ' . URLROOT . '/support/index');
            exit;
        }
    }

    public function resolve($id = null): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && $id) {
            $ticketId = (int)$id;

            if ($this->supportModel->markResolved($ticketId, (int)$_SESSION['user_id'])) {
                systemLog('SUPPORT_TICKET_RESOLVED', "User {$_SESSION['user_email']} marked ticket ID {$ticketId} as resolved.");
                flash('system_msg', 'Ticket successfully marked as Resolved!', 'success');
            } else {
                flash('system_msg', 'Could not update ticket status.', 'error');
            }
            header('Location: ' . URLROOT . '/support/index');
            exit;
        } else {
            header('Location: ' . URLROOT . '/support/index');
            exit;
        }
    }
}