<?php declare(strict_types=1);
// Christo Lochenberg Developments | info@christodev.co.za | +27 61 523 9126

class AdminSettings extends Controller {
    
    public function __construct() {
        if (!isLoggedIn() || !isAdmin()) {
            header('Location: ' . URLROOT . '/users/login');
            exit;
        }
    }

    public function settings(): void {
        $settingModel = $this->model('Setting');
        $currentSettings = getSettings();
        
        $vFile = dirname(__DIR__, 2) . '/version.php';
        $appVersion = file_exists($vFile) ? include $vFile : '1.0.0';
        
        $db = new Database();
        $db->query("SELECT VERSION() as version");
        $mysql_version = $db->single()->version ?? 'Unknown';

        $extensions = ['pdo', 'pdo_mysql', 'mbstring', 'curl', 'openssl', 'json', 'zip', 'gd', 'xml'];
        $ext_status = [];
        foreach ($extensions as $ext) {
            $ext_status[$ext] = extension_loaded($ext);
        }

        $keyFile = dirname(__DIR__, 2) . '/config/license.key';
        $licenseKey = file_exists($keyFile) ? trim(file_get_contents($keyFile)) : 'UNKNOWN';

        $data = [
            'title' => 'Application Settings',
            'description' => 'Configure your app globally here.',
            'settings' => $currentSettings,
            'system' => [
                'php_version' => PHP_VERSION,
                'mysql_version' => $mysql_version,
                'app_version' => $appVersion,
                'db_version' => $currentSettings['db_version'] ?? '0',
                'extensions' => $ext_status,
                'license_key' => $licenseKey,
                'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'
            ],
            
            // Contextual Help
            'help_title' => 'Global Configuration Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">Global Configuration</h4>
                <p>This dashboard controls the fundamental behavior and branding of your entire application.</p>
                <ul class="list-disc pl-5 space-y-2 mt-2">
                    <li><strong>General & Contact:</strong> Manage your app\'s name, SEO metadata, address details, and core access toggles (Registration and Maintenance Mode).</li>
                    <li><strong>Branding:</strong> Upload your light/dark mode logos and set the primary UI color. Changes here trigger a dynamic re-compilation of the Tailwind CSS classes across the entire platform.</li>
                    <li><strong>Legal Pages:</strong> Define the HTML content for your public-facing Terms of Service and Privacy Policy. These sync automatically to the frontend views.</li>
                    <li><strong>Email/SMTP:</strong> Configure your outbound mail server. This is critical for password resets and system notifications. You can use the "Send Test Email" tool to verify your credentials.</li>
                    <li><strong>System Info:</strong> View your server\'s health, PHP/MySQL versions, missing extensions, and active license details. If you encounter issues, you can send a 1-click diagnostic report to developer support from this tab.</li>
                </ul>
            '
        ];

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            
            if (isset($_POST['action_type']) && $_POST['action_type'] === 'test_email') {
                $testEmail = trim($_POST['test_email_address']);
                if (!empty($testEmail)) {
                    $body = "<h2>System Email Test</h2><p>If you are receiving this, your SMTP configuration inside the App Development Template is working correctly.</p>";
                    sendEmail($testEmail, "SMTP Configuration Test", $body);
                    processEmailQueue(5);
                    flash('system_msg', 'Test email has been sent. Check your inbox.', 'success');
                } else {
                    flash('system_msg', 'Please provide an email address to send the test to.', 'error');
                }
                header('Location: ' . URLROOT . '/admin/settings?tab=email');
                exit;
            }

            if (isset($_POST['action_type']) && $_POST['action_type'] === 'send_diagnostics') {
                $appName = $currentSettings['app_name'] ?? SITENAME;
                $adminName = $_SESSION['user_name'];
                $adminEmail = $_SESSION['user_email'];

                $logDir = dirname(__DIR__, 2) . '/logs';
                $errorLogPath = $logDir . '/error.log';
                $uploadsDir = dirname(__DIR__, 2) . '/public/uploads';

                $isLogWritable = is_writable($logDir);
                $isUploadsWritable = is_writable($uploadsDir);

                $logWritable = $isLogWritable ? 'Writable' : 'Not Writable';
                $uploadsWritable = $isUploadsWritable ? 'Writable' : 'Not Writable';

                require_once dirname(__DIR__) . '/Core/AppClient.php';
                $serverUrl = 'https://license.christodev.co.za';
                $cacheDir = dirname(__DIR__, 2) . '/public/cache';
                $client = new AppClient($serverUrl, $data['system']['license_key'], $data['system']['app_version'], $cacheDir);
                $updateInfo = $client->checkUpdates();

                $updateStatus = "Up to date";
                $updateColor = "#10b981"; 
                if (isset($updateInfo->update_available) && $updateInfo->update_available) {
                    $updateStatus = "Update Available (v" . htmlspecialchars($updateInfo->new_version) . ")";
                    $updateColor = "#ef4444";
                }

                $devSupportStatus = (isset($currentSettings['allow_developer_support']) && $currentSettings['allow_developer_support'] === '1') 
                    ? '<span style="color:#10b981; font-weight:bold;">Enabled</span>' 
                    : '<span style="color:#ef4444; font-weight:bold;">Disabled</span>';

                $body = "<h2 style='color:#1f2937; margin-top:0;'>System Diagnostics Report</h2>";
                $body .= "<p><strong>App Name:</strong> {$appName}</p>";
                $body .= "<p><strong>Live URL:</strong> <a href='" . URLROOT . "'>" . URLROOT . "</a></p>";
                $body .= "<p><strong>Admin Triggered By:</strong> {$adminName} ({$adminEmail})</p>";
                $body .= "<p><strong>License Key:</strong> {$data['system']['license_key']}</p>";
                $body .= "<p><strong>Developer Support Access:</strong> {$devSupportStatus}</p>";
                
                $body .= "<h3 style='color:#1f2937; margin-top:20px; border-bottom: 1px solid #e5e7eb; padding-bottom: 5px;'>System Versions</h3>";
                $body .= "<ul>";
                $body .= "<li><strong>App Version:</strong> v{$data['system']['app_version']} <span style='color:{$updateColor}; font-weight:bold;'>[{$updateStatus}]</span></li>";
                $body .= "<li><strong>Database Version:</strong> v{$data['system']['db_version']}</li>";
                $body .= "<li><strong>PHP Version:</strong> {$data['system']['php_version']}</li>";
                $body .= "<li><strong>MySQL Version:</strong> {$data['system']['mysql_version']}</li>";
                $body .= "<li><strong>Server Software:</strong> {$data['system']['server_software']}</li>";
                $body .= "</ul>";

                $body .= "<h3 style='color:#1f2937; margin-top:20px; border-bottom: 1px solid #e5e7eb; padding-bottom: 5px;'>Directory Status</h3>";
                $body .= "<ul>";
                $body .= "<li><strong>/logs directory:</strong> {$logWritable}</li>";
                $body .= "<li><strong>/public/uploads directory:</strong> {$uploadsWritable}</li>";
                $body .= "</ul>";

                $body .= "<h3 style='color:#1f2937; margin-top:20px; border-bottom: 1px solid #e5e7eb; padding-bottom: 5px;'>PHP Extensions</h3>";
                $body .= "<ul>";
                foreach ($data['system']['extensions'] as $ext => $isLoaded) {
                    $status = $isLoaded ? 'Enabled' : 'Disabled';
                    $color = $isLoaded ? '#10b981' : '#ef4444'; 
                    $body .= "<li><strong>{$ext}:</strong> <span style='color:{$color}; font-weight: bold;'>{$status}</span></li>";
                }
                $body .= "</ul>";

                $recommendations = [];
                if (!$isLogWritable) {
                    $recommendations[] = "<strong>Logs Directory:</strong> The <code>/logs</code> directory is not writable or is missing. Please create this folder in the root directory and set permissions to 0755 to ensure fatal errors are safely logged.";
                }
                if (!$isUploadsWritable) {
                    $recommendations[] = "<strong>Uploads Directory:</strong> The <code>/public/uploads</code> directory is not writable. Please verify folder permissions so branding assets (logos/favicons) can be uploaded.";
                }
                
                $missingExts = [];
                foreach ($data['system']['extensions'] as $ext => $isLoaded) {
                    if (!$isLoaded) { $missingExts[] = $ext; }
                }
                if (!empty($missingExts)) {
                    $recommendations[] = "<strong>PHP Extensions:</strong> The following required extensions are missing or disabled: <strong>" . implode(', ', $missingExts) . "</strong>. Please enable them in your php.ini or cPanel configuration.";
                }

                if (isset($updateInfo->update_available) && $updateInfo->update_available) {
                    $recommendations[] = "<strong>Software Update:</strong> A new OTA update (v{$updateInfo->new_version}) is available. Please navigate to the 'License & Updates' tab in your admin dashboard to securely download and install it.";
                }

                $body .= "<h3 style='color:#1f2937; margin-top:20px; border-bottom: 1px solid #e5e7eb; padding-bottom: 5px;'>Recommended Actions</h3>";
                if (empty($recommendations)) {
                    $body .= "<p style='color:#10b981; font-weight:bold;'>&#10003; All systems are optimal. No action required.</p>";
                } else {
                    $body .= "<ul>";
                    foreach ($recommendations as $rec) { $body .= "<li style='margin-bottom:10px; color:#ef4444;'>{$rec}</li>"; }
                    $body .= "</ul>";
                }

                $attachments = [];
                if (file_exists($errorLogPath) && filesize($errorLogPath) > 0) {
                    $attachments[] = $errorLogPath;
                }

                if (sendEmail('support@christodev.co.za', "Diagnostics Report: {$appName}", $body, $attachments)) {
                    processEmailQueue(5);
                    systemLog('DIAGNOSTICS_SENT', 'Admin generated and sent a system diagnostics report to support.');
                    flash('system_msg', 'System diagnostics have been compiled and sent to developer support.', 'success');
                } else {
                    flash('system_msg', 'Failed to queue diagnostics. Please check your SMTP configuration.', 'error');
                }

                header('Location: ' . URLROOT . '/admin/settings?tab=system');
                exit;
            }

            // --- Toggle Captures ---
            $allow_registration = isset($_POST['allow_registration']) ? '1' : '0';
            $maintenance_mode = isset($_POST['maintenance_mode']) ? '1' : '0';
            $smtp_bcc_enable = isset($_POST['smtp_bcc_enable']) ? '1' : '0';
            $allow_developer_support = isset($_POST['allow_developer_support']) ? '1' : '0';

            // --- General & Branding Updates ---
            $settingModel->updateSetting('allow_registration', $allow_registration);
            $settingModel->updateSetting('maintenance_mode', $maintenance_mode);
            $settingModel->updateSetting('allow_developer_support', $allow_developer_support);
            
            $settingModel->updateSetting('app_name', trim($_POST['app_name']));
            $settingModel->updateSetting('seo_description', trim($_POST['seo_description']));
            $settingModel->updateSetting('seo_keywords', trim($_POST['seo_keywords']));
            $settingModel->updateSetting('theme_color', trim($_POST['theme_color']));
            
            $settingModel->updateSetting('privacy_policy', trim($_POST['privacy_policy']));
            $settingModel->updateSetting('terms_of_service', trim($_POST['terms_of_service']));
            
            $settingModel->updateSetting('contact_email', trim($_POST['contact_email']));
            $settingModel->updateSetting('contact_landline', trim($_POST['contact_landline'] ?? ''));
            $settingModel->updateSetting('contact_mobile', trim($_POST['contact_mobile'] ?? ''));
            
            $settingModel->updateSetting('contact_address_street', trim($_POST['contact_address_street'] ?? ''));
            $settingModel->updateSetting('contact_address_suburb', trim($_POST['contact_address_suburb'] ?? ''));
            $settingModel->updateSetting('contact_address_city', trim($_POST['contact_address_city'] ?? ''));
            $settingModel->updateSetting('contact_address_state', trim($_POST['contact_address_state'] ?? ''));
            $settingModel->updateSetting('contact_address_zip', trim($_POST['contact_address_zip'] ?? ''));
            $settingModel->updateSetting('contact_address_country', trim($_POST['contact_address_country'] ?? ''));

            $settingModel->updateSetting('smtp_host', trim($_POST['smtp_host']));
            $settingModel->updateSetting('smtp_port', trim($_POST['smtp_port']));
            $settingModel->updateSetting('smtp_encryption', trim($_POST['smtp_encryption'] ?? ''));
            $settingModel->updateSetting('smtp_user', trim($_POST['smtp_user']));
            if (!empty($_POST['smtp_pass'])) {
                $settingModel->updateSetting('smtp_pass', trim($_POST['smtp_pass']));
            }
            $settingModel->updateSetting('smtp_from_name', trim($_POST['smtp_from_name']));
            $settingModel->updateSetting('smtp_from_email', trim($_POST['smtp_from_email']));
            $settingModel->updateSetting('smtp_bcc_enable', $smtp_bcc_enable);
            $settingModel->updateSetting('smtp_bcc_email', trim($_POST['smtp_bcc_email']));

            $uploadDir = '../public/uploads/';
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/x-icon', 'image/webp'];
            $filesToProcess = ['logo_light', 'logo_dark', 'favicon'];
            
            foreach ($filesToProcess as $fileKey) {
                if (!empty($_FILES[$fileKey]['name']) && $_FILES[$fileKey]['error'] === 0) {
                    $fileType = mime_content_type($_FILES[$fileKey]['tmp_name']);
                    if (in_array($fileType, $allowedTypes)) {
                        $ext = pathinfo($_FILES[$fileKey]['name'], PATHINFO_EXTENSION);
                        $filename = $fileKey . '_' . time() . '.' . $ext;
                        if (move_uploaded_file($_FILES[$fileKey]['tmp_name'], $uploadDir . $filename)) {
                            $settingModel->updateSetting($fileKey, $filename);
                        }
                    }
                }
            }

            systemLog('SETTINGS_UPDATED', 'Admin updated global application settings.');
            flash('system_msg', 'Settings successfully updated!', 'success');
            
            $activeTab = $_POST['active_tab'] ?? 'general';
            header('Location: ' . URLROOT . '/admin/settings?tab=' . $activeTab);
            exit;
        }

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