<?php declare(strict_types=1);

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

class Pages extends Controller {
    
    public function __construct() {
        // Publicly accessible, no login required!
    }

    public function index(): void {
        $data = ['title' => 'Welcome to ' . (getSettings()['app_name'] ?? SITENAME)];
        $this->view('pages/index', $data);
    }

    public function privacy(): void {
        $data = ['title' => 'Privacy Policy'];
        $this->view('pages/privacy', $data);
    }

    public function terms(): void {
        $data = ['title' => 'Terms of Service'];
        $this->view('pages/terms', $data);
    }

    // --- NEW: The Maintenance Method ---
    public function maintenance(): void {
        // Send a 503 header so search engines know it's a temporary outage and don't penalize SEO
        header('HTTP/1.1 503 Service Temporarily Unavailable');
        header('Status: 503 Service Temporarily Unavailable');
        header('Retry-After: 3600');

        $data = [
            'title' => 'System Maintenance',
            'description' => 'We are currently upgrading our systems. We will be back shortly.'
        ];
        $this->view('pages/maintenance', $data);
    }

    // --- Dynamic PWA Manifest Generator ---
    public function manifest(): void {
        header('Content-Type: application/json');
        $settings = getSettings();
        
        $appName = $settings['app_name'] ?? SITENAME;
        $themeColor = $settings['theme_color'] ?? '#15699e';
        $description = $settings['seo_description'] ?? 'A powerful software application.';
        
        // Strict Requirement: Use Favicon for the App Icon
        $iconUrl = !empty($settings['favicon']) ? URLROOT . '/uploads/' . $settings['favicon'] : URLROOT . '/uploads/brand/icon.png';

        $manifest = [
            'name' => $appName,
            'short_name' => $appName,
            'description' => $description,
            'start_url' => URLROOT . '/',
            'display' => 'standalone',
            'background_color' => '#ffffff',
            'theme_color' => $themeColor,
            'icons' => [
                [
                    'src' => $iconUrl,
                    'sizes' => '192x192 512x512',
                    'type' => 'image/png',
                    'purpose' => 'any maskable'
                ]
            ]
        ];

        echo json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        exit;
    }

    public function contact(): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            
            $data = [
                'title' => 'Contact Us',
                'name' => trim($_POST['name'] ?? ''),
                'email' => trim($_POST['email'] ?? ''),
                'subject' => trim($_POST['subject'] ?? ''),
                'message' => trim($_POST['message'] ?? ''),
                'captcha' => trim($_POST['captcha'] ?? ''),
                'name_err' => '',
                'email_err' => '',
                'subject_err' => '',
                'message_err' => '',
                'captcha_err' => ''
            ];

            if (empty($data['name'])) { $data['name_err'] = 'Please enter your name.'; }
            if (empty($data['email'])) { $data['email_err'] = 'Please enter your email.'; }
            if (empty($data['subject'])) { $data['subject_err'] = 'Please enter a subject.'; }
            if (empty($data['message'])) { $data['message_err'] = 'Please enter your message.'; }
            
            // Validate Captcha
            if (empty($data['captcha']) || !validateCaptcha($data['captcha'])) {
                $data['captcha_err'] = 'Incorrect CAPTCHA answer. Please try again.';
            }

            // If no errors, queue the email
            if (empty($data['name_err']) && empty($data['email_err']) && empty($data['subject_err']) && empty($data['message_err']) && empty($data['captcha_err'])) {
                
                $settings = getSettings();
                $to = $settings['contact_email'] ?? 'info@christodev.co.za';
                $emailSubject = "New Contact Form Submission: " . $data['subject'];
                
                // Build the email body using the global template wrapper
                $body = "<h2 style='color:#1f2937; margin-top:0;'>New Website Enquiry</h2>";
                $body .= "<p><strong>Name:</strong> {$data['name']}</p>";
                $body .= "<p><strong>Email:</strong> {$data['email']}</p>";
                $body .= "<hr style='border:none; border-top:1px solid #e5e7eb; margin: 20px 0;'>";
                $body .= "<p><strong>Message:</strong></p>";
                $body .= "<p style='white-space: pre-wrap; font-family: monospace; background: #f9fafb; padding: 15px; border-radius: 5px; border: 1px solid #e5e7eb;'>" . htmlspecialchars($data['message']) . "</p>";

                if (sendEmail($to, $emailSubject, $body)) {
                    systemLog('CONTACT_FORM_SUBMITTED', "Public contact form submitted by: {$data['email']}");
                    flash('system_msg', 'Your message has been queued successfully! We will get back to you shortly.', 'success');
                    header('Location: ' . URLROOT . '/pages/contact');
                    exit;
                } else {
                    flash('system_msg', 'There was an error sending your message. Please try again later.', 'error');
                }
            }
            
            // Validation failed, regenerate captcha and show errors
            $captcha = generateMathCaptcha();
            $data['captcha_num1'] = $captcha['num1'];
            $data['captcha_num2'] = $captcha['num2'];
            $this->view('pages/contact', $data);
            
        } else {
            // Initial Load
            $captcha = generateMathCaptcha();
            $data = [
                'title' => 'Contact Us',
                'name' => '', 'email' => '', 'subject' => '', 'message' => '', 'captcha' => '',
                'name_err' => '', 'email_err' => '', 'subject_err' => '', 'message_err' => '', 'captcha_err' => '',
                'captcha_num1' => $captcha['num1'],
                'captcha_num2' => $captcha['num2']
            ];
            $this->view('pages/contact', $data);
        }
    }

    // ==========================================
    // USER PROFILE METHODS (STAFF & CLIENTS)
    // ==========================================
    
    public function profile(): void {
        if (!isLoggedIn()) {
            header('Location: ' . URLROOT . '/users/login');
            exit;
        }
        
        // Admins have their own profile in the Admin controller
        if (isAdmin()) {
            header('Location: ' . URLROOT . '/admin/profile');
            exit;
        }

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

        $data = [
            'title' => 'My Profile',
            'user' => $user, // Pass the full object to view so company_name and staff_role_name are accessible
            'name' => $user->name,
            'email' => $user->email,
            'totp_enabled' => $user->totp_enabled,
            'name_err' => '',
            'email_err' => '',
            'qr_code_url' => '',
            'setup_secret' => '',
            'help_title' => 'Managing Your Profile',
            'help_content' => '<p>Update your personal details here. We highly recommend activating <strong>Two-Factor Authentication (2FA)</strong> to secure your account. Once activated, ensure you copy your single-use backup codes and store them safely.</p>'
        ];

        if (isset($_GET['setup2fa']) && $user->totp_enabled == 0) {
            $data['setup_secret'] = generateTOTPSecret();
            $appName = getSettings()['app_name'] ?? SITENAME;
            $data['qr_code_url'] = getTOTPQRCodeUrl($appName, $user->email, $data['setup_secret']);
        }

        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_info'])) {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

            $data['name'] = trim($_POST['name']);
            $data['email'] = trim($_POST['email']);

            if (empty($data['email'])) {
                $data['email_err'] = 'Please enter an email address';
            } elseif ($data['email'] != $user->email && $userModel->findUserByEmail($data['email'])) {
                $data['email_err'] = 'This email is already taken by another account';
            }

            if (empty($data['name'])) {
                $data['name_err'] = 'Please enter your name';
            }

            if (empty($data['email_err']) && empty($data['name_err'])) {
                $updateData = ['id' => $_SESSION['user_id'], 'name' => $data['name'], 'email' => $data['email']];
                
                if ($userModel->updateProfile($updateData)) {
                    $_SESSION['user_name'] = $data['name'];
                    $_SESSION['user_email'] = $data['email'];

                    systemLog('PROFILE_UPDATED', 'User updated their personal profile.');
                    flash('system_msg', 'Profile updated successfully!', 'success');
                    
                    header('Location: ' . URLROOT . '/profile/index');
                    exit;
                }
            }
        }

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