<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Fetch user details
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details || $user_details['role_name'] !== 'Administrator') {
    header('Location: index.php');
    exit();
}

$full_name = $user_details['full_name'];
$role_name = $user_details['role_name'];

// Handle form submission
if ($_POST) {
    header('Content-Type: application/json');
    
    try {
        $conn->begin_transaction();
        
        $updated_count = 0;
        $error_count = 0;
        
        foreach ($_POST as $key => $value) {
            if ($key === 'action') continue;
            
            // Sanitize the value
            $clean_value = trim($value);
            
            // Update or insert setting
            $sql_setting = "INSERT INTO settings (setting_key, setting_value, updated_at) 
                           VALUES (?, ?, NOW()) 
                           ON DUPLICATE KEY UPDATE 
                           setting_value = VALUES(setting_value), 
                           updated_at = NOW()";
            
            $stmt_setting = $conn->prepare($sql_setting);
            $stmt_setting->bind_param("ss", $key, $clean_value);
            
            if ($stmt_setting->execute()) {
                $updated_count++;
            } else {
                $error_count++;
            }
        }
        
        // Log activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                   VALUES (?, 'UPDATE', 'settings', 'system_settings', ?)";
        $stmt_log = $conn->prepare($log_sql);
        $log_details = json_encode(['settings_updated' => $updated_count, 'timestamp' => date('Y-m-d H:i:s')]);
        $stmt_log->bind_param("is", $user_id, $log_details);
        $stmt_log->execute();
        
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => "Settings updated successfully ($updated_count settings)",
            'updated' => $updated_count,
            'errors' => $error_count
        ]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => 'Error updating settings: ' . $e->getMessage()]);
    }
    exit();
}

// Fetch all settings
$sql_settings = "SELECT setting_key, setting_value, description, category 
                 FROM settings 
                 ORDER BY category, setting_key";
$result_settings = $conn->query($sql_settings);

$settings = [];
while ($row = $result_settings->fetch_assoc()) {
    $settings[$row['category']][$row['setting_key']] = [
        'value' => $row['setting_value'],
        'description' => $row['description']
    ];
}

// Helper function
function getSetting($settings, $category, $key, $default = '') {
    return $settings[$category][$key]['value'] ?? $default;
}

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'System Settings - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .settings-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .settings-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            margin-bottom: 1.5rem;
            overflow: hidden;
        }
        
        .settings-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }
        
        .settings-tab-header {
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            padding: 1.5rem;
        }
        
        .settings-tab-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
            display: flex;
            align-items: center;
        }
        
        .settings-tab-title i {
            margin-right: 0.75rem;
            font-size: 1.25rem;
        }
        
        .settings-form-section {
            padding: 1.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .form-label i {
            color: #6b7280;
            font-size: 0.875rem;
        }
        
        .form-control {
            border-radius: 8px;
            border: 1px solid #d1d5db;
            padding: 0.75rem 1rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .form-text {
            color: #6b7280;
            font-size: 0.875rem;
            margin-top: 0.5rem;
        }
        
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }
        
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #cbd5e1;
            transition: 0.4s;
            border-radius: 24px;
        }
        
        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: 0.4s;
            border-radius: 50%;
        }
        
        input:checked + .toggle-slider {
            background-color: #667eea;
        }
        
        input:checked + .toggle-slider:before {
            transform: translateX(26px);
        }
        
        .save-button {
            background: linear-gradient(45deg, #10b981, #059669);
            color: white;
            border: none;
            padding: 0.75rem 2rem;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            z-index: 1000;
        }
        
        .save-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
        }
        
        .currency-preview {
            background: #f0f9ff;
            border: 1px solid #0ea5e9;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 0.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .currency-preview-amount {
            font-weight: 600;
            color: #0c4a6e;
        }
        
        .nav-tabs .nav-link {
            border: none;
            border-radius: 8px;
            margin-right: 0.5rem;
            padding: 0.75rem 1.5rem;
            color: #64748b;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .nav-tabs .nav-link:hover {
            background: #f1f5f9;
            color: #334155;
        }
        
        .nav-tabs .nav-link.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }
        
        .tab-content {
            margin-top: 1.5rem;
        }
        
        .settings-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
        }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .settings-header {
                padding: 1.5rem;
            }
            
            .save-button {
                position: static;
                width: 100%;
                margin-top: 2rem;
            }
            
            .settings-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="settings-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h2 class="mb-2">
                                    <i class="ri-settings-3-line me-2"></i>System Settings
                                </h2>
                                <p class="mb-0 opacity-90">Configure your freight management system settings and preferences</p>
                            </div>
                            <div class="text-end">
                                <div class="fw-bold">Last Updated</div>
                                <div class="opacity-80"><?php echo date('M j, Y H:i'); ?></div>
                            </div>
                        </div>
                    </div>

                    <!-- Settings Navigation Tabs -->
                    <ul class="nav nav-tabs" id="settingsTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="company-tab" data-bs-toggle="tab" data-bs-target="#company" type="button" role="tab">
                                <i class="ri-building-line me-2"></i>Company
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="system-tab" data-bs-toggle="tab" data-bs-target="#system" type="button" role="tab">
                                <i class="ri-computer-line me-2"></i>System
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="financial-tab" data-bs-toggle="tab" data-bs-target="#financial" type="button" role="tab">
                                <i class="ri-money-dollar-circle-line me-2"></i>Financial
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="shipping-tab" data-bs-toggle="tab" data-bs-target="#shipping" type="button" role="tab">
                                <i class="ri-truck-line me-2"></i>Shipping
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="email-tab" data-bs-toggle="tab" data-bs-target="#email" type="button" role="tab">
                                <i class="ri-mail-line me-2"></i>Email
                            </button>
                        </li>
                    </ul>

                    <!-- Settings Form -->
                    <form id="settingsForm" method="POST">
                        <div class="tab-content" id="settingsTabContent">
                            
                            <!-- Company Settings -->
                            <div class="tab-pane fade show active" id="company" role="tabpanel">
                                <div class="settings-card">
                                    <div class="settings-tab-header">
                                        <h5 class="settings-tab-title">
                                            <i class="ri-building-line"></i>Company Information
                                        </h5>
                                    </div>
                                    <div class="settings-form-section">
                                        <div class="settings-grid">
                                            <div class="form-group">
                                                <label for="company_name" class="form-label">
                                                    <i class="ri-building-2-line"></i>Company Name
                                                </label>
                                                <input type="text" class="form-control" id="company_name" name="company_name" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'company', 'company_name', 'Polakis Technologies Ltd')); ?>">
                                                <div class="form-text">Your company name as it appears on documents and invoices</div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_address" class="form-label">
                                                    <i class="ri-map-pin-line"></i>Address
                                                </label>
                                                <input type="text" class="form-control" id="company_address" name="company_address" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'company', 'company_address', 'Nanak House, Kimathi Street')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_city" class="form-label">
                                                    <i class="ri-building-3-line"></i>City
                                                </label>
                                                <input type="text" class="form-control" id="company_city" name="company_city" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'company', 'company_city', 'Nairobi')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_country" class="form-label">
                                                    <i class="ri-global-line"></i>Country
                                                </label>
                                                <input type="text" class="form-control" id="company_country" name="company_country" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'company', 'company_country', 'Kenya')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_phone" class="form-label">
                                                    <i class="ri-phone-line"></i>Primary Phone Number
                                                </label>
                                                <input type="text" class="form-control" id="company_phone" name="company_phone" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'company', 'company_phone', '+254798805300')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_phone_2" class="form-label">
                                                    <i class="ri-phone-line"></i>Secondary Phone Number
                                                </label>
                                                <input type="text" class="form-control" id="company_phone_2" name="company_phone_2" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'company', 'company_phone_2', '')); ?>"
                                                       placeholder="Optional secondary phone">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_email" class="form-label">
                                                    <i class="ri-mail-line"></i>Email Address
                                                </label>
                                                <input type="email" class="form-control" id="company_email" name="company_email" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'company', 'company_email', 'info@polakis.co.ke')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_website" class="form-label">
                                                    <i class="ri-earth-line"></i>Website
                                                </label>
                                                <input type="url" class="form-control" id="company_website" name="company_website" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'company', 'company_website', 'https://www.polakis.co.ke')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_tax_id" class="form-label">
                                                    <i class="ri-file-text-line"></i>Tax ID / Registration Number
                                                </label>
                                                <input type="text" class="form-control" id="company_tax_id" name="company_tax_id" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'company', 'company_tax_id', 'TAX12345')); ?>">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- System Settings -->
                            <div class="tab-pane fade" id="system" role="tabpanel">
                                <div class="settings-card">
                                    <div class="settings-tab-header">
                                        <h5 class="settings-tab-title">
                                            <i class="ri-computer-line"></i>System Configuration
                                        </h5>
                                    </div>
                                    <div class="settings-form-section">
                                        <div class="settings-grid">
                                            <div class="form-group">
                                                <label for="system_name" class="form-label">
                                                    <i class="ri-window-line"></i>System Name
                                                </label>
                                                <input type="text" class="form-control" id="system_name" name="system_name" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'system', 'system_name', 'Freight Management System')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="timezone" class="form-label">
                                                    <i class="ri-time-zone-line"></i>Timezone
                                                </label>
                                                <select class="form-control" id="timezone" name="timezone">
                                                    <option value="Africa/Nairobi" <?php echo getSetting($settings, 'system', 'timezone', 'Africa/Nairobi') == 'Africa/Nairobi' ? 'selected' : ''; ?>>East Africa Time (Nairobi)</option>
                                                    <option value="UTC" <?php echo getSetting($settings, 'system', 'timezone') == 'UTC' ? 'selected' : ''; ?>>UTC</option>
                                                    <option value="America/New_York" <?php echo getSetting($settings, 'system', 'timezone') == 'America/New_York' ? 'selected' : ''; ?>>Eastern Time</option>
                                                    <option value="Europe/London" <?php echo getSetting($settings, 'system', 'timezone') == 'Europe/London' ? 'selected' : ''; ?>>GMT</option>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="date_format" class="form-label">
                                                    <i class="ri-calendar-line"></i>Date Format
                                                </label>
                                                <select class="form-control" id="date_format" name="date_format">
                                                    <option value="Y-m-d" <?php echo getSetting($settings, 'system', 'date_format', 'Y-m-d') == 'Y-m-d' ? 'selected' : ''; ?>>YYYY-MM-DD</option>
                                                    <option value="m/d/Y" <?php echo getSetting($settings, 'system', 'date_format') == 'm/d/Y' ? 'selected' : ''; ?>>MM/DD/YYYY</option>
                                                    <option value="d/m/Y" <?php echo getSetting($settings, 'system', 'date_format') == 'd/m/Y' ? 'selected' : ''; ?>>DD/MM/YYYY</option>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="items_per_page" class="form-label">
                                                    <i class="ri-list-check"></i>Items Per Page
                                                </label>
                                                <select class="form-control" id="items_per_page" name="items_per_page">
                                                    <option value="10" <?php echo getSetting($settings, 'system', 'items_per_page') == '10' ? 'selected' : ''; ?>>10</option>
                                                    <option value="25" <?php echo getSetting($settings, 'system', 'items_per_page', '25') == '25' ? 'selected' : ''; ?>>25</option>
                                                    <option value="50" <?php echo getSetting($settings, 'system', 'items_per_page') == '50' ? 'selected' : ''; ?>>50</option>
                                                    <option value="100" <?php echo getSetting($settings, 'system', 'items_per_page') == '100' ? 'selected' : ''; ?>>100</option>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="session_timeout" class="form-label">
                                                    <i class="ri-timer-line"></i>Session Timeout (minutes)
                                                </label>
                                                <input type="number" class="form-control" id="session_timeout" name="session_timeout" 
                                                       value="<?php echo getSetting($settings, 'system', 'session_timeout', '30'); ?>" min="5" max="480">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-tools-line"></i>Maintenance Mode
                                                </label>
                                                <div class="d-flex align-items-center">
                                                    <label class="toggle-switch">
                                                        <input type="checkbox" name="maintenance_mode" value="on" 
                                                               <?php echo getSetting($settings, 'system', 'maintenance_mode') == 'on' ? 'checked' : ''; ?>>
                                                        <span class="toggle-slider"></span>
                                                    </label>
                                                    <span class="ms-3">Enable maintenance mode</span>
                                                </div>
                                                <div class="form-text">When enabled, only administrators can access the system</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Financial Settings -->
                            <div class="tab-pane fade" id="financial" role="tabpanel">
                                <div class="settings-card">
                                    <div class="settings-tab-header">
                                        <h5 class="settings-tab-title">
                                            <i class="ri-money-dollar-circle-line"></i>Financial Configuration
                                        </h5>
                                    </div>
                                    <div class="settings-form-section">
                                        <div class="settings-grid">
                                            <div class="form-group">
                                                <label for="default_currency" class="form-label">
                                                    <i class="ri-money-cny-circle-line"></i>Default Currency
                                                </label>
                                                <select class="form-control" id="default_currency" name="default_currency" onchange="updateCurrencyPreview()">
                                                    <option value="KES" <?php echo getSetting($settings, 'financial', 'default_currency', 'KES') == 'KES' ? 'selected' : ''; ?>>KES - Kenyan Shilling</option>
                                                    <option value="USD" <?php echo getSetting($settings, 'financial', 'default_currency') == 'USD' ? 'selected' : ''; ?>>USD - US Dollar</option>
                                                    <option value="EUR" <?php echo getSetting($settings, 'financial', 'default_currency') == 'EUR' ? 'selected' : ''; ?>>EUR - Euro</option>
                                                    <option value="GBP" <?php echo getSetting($settings, 'financial', 'default_currency') == 'GBP' ? 'selected' : ''; ?>>GBP - British Pound</option>
                                                    <option value="UGX" <?php echo getSetting($settings, 'financial', 'default_currency') == 'UGX' ? 'selected' : ''; ?>>UGX - Ugandan Shilling</option>
                                                    <option value="TZS" <?php echo getSetting($settings, 'financial', 'default_currency') == 'TZS' ? 'selected' : ''; ?>>TZS - Tanzanian Shilling</option>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="currency_symbol" class="form-label">
                                                    <i class="ri-currency-line"></i>Currency Symbol
                                                </label>
                                                <input type="text" class="form-control" id="currency_symbol" name="currency_symbol" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'financial', 'currency_symbol', 'KSh')); ?>" maxlength="5">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="currency_position" class="form-label">
                                                    <i class="ri-align-left"></i>Currency Position
                                                </label>
                                                <select class="form-control" id="currency_position" name="currency_position">
                                                    <option value="before" <?php echo getSetting($settings, 'financial', 'currency_position', 'before') == 'before' ? 'selected' : ''; ?>>Before Amount</option>
                                                    <option value="after" <?php echo getSetting($settings, 'financial', 'currency_position') == 'after' ? 'selected' : ''; ?>>After Amount</option>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="decimal_places" class="form-label">
                                                    <i class="ri-number-2"></i>Decimal Places
                                                </label>
                                                <select class="form-control" id="decimal_places" name="decimal_places">
                                                    <option value="0" <?php echo getSetting($settings, 'financial', 'decimal_places') == '0' ? 'selected' : ''; ?>>0</option>
                                                    <option value="2" <?php echo getSetting($settings, 'financial', 'decimal_places', '2') == '2' ? 'selected' : ''; ?>>2</option>
                                                    <option value="3" <?php echo getSetting($settings, 'financial', 'decimal_places') == '3' ? 'selected' : ''; ?>>3</option>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="default_payment_terms" class="form-label">
                                                    <i class="ri-calendar-check-line"></i>Default Payment Terms (Days)
                                                </label>
                                                <input type="number" class="form-control" id="default_payment_terms" name="default_payment_terms" 
                                                       value="<?php echo getSetting($settings, 'financial', 'default_payment_terms', '30'); ?>" min="1" max="365">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="tax_calculation" class="form-label">
                                                    <i class="ri-calculator-line"></i>Tax Calculation Method
                                                </label>
                                                <select class="form-control" id="tax_calculation" name="tax_calculation">
                                                    <option value="inclusive" <?php echo getSetting($settings, 'financial', 'tax_calculation', 'inclusive') == 'inclusive' ? 'selected' : ''; ?>>Tax Inclusive</option>
                                                    <option value="exclusive" <?php echo getSetting($settings, 'financial', 'tax_calculation') == 'exclusive' ? 'selected' : ''; ?>>Tax Exclusive</option>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <!-- Currency Preview -->
                                        <div class="currency-preview" id="currencyPreview">
                                            <div>
                                                <strong>Currency Preview:</strong>
                                            </div>
                                            <div class="currency-preview-amount" id="currencyPreviewAmount">
                                                KSh 1,234.56
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Shipping Settings -->
                            <div class="tab-pane fade" id="shipping" role="tabpanel">
                                <div class="settings-card">
                                    <div class="settings-tab-header">
                                        <h5 class="settings-tab-title">
                                            <i class="ri-truck-line"></i>Shipping Configuration
                                        </h5>
                                    </div>
                                    <div class="settings-form-section">
                                        <div class="settings-grid">
                                            <div class="form-group">
                                                <label for="tracking_number_prefix" class="form-label">
                                                    <i class="ri-barcode-line"></i>Tracking Number Prefix
                                                </label>
                                                <input type="text" class="form-control" id="tracking_number_prefix" name="tracking_number_prefix" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'shipping', 'tracking_number_prefix', 'TRK')); ?>" maxlength="5">
                                                <div class="form-text">Prefix for tracking numbers (e.g., TRK, SHIP, FRT)</div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="tracking_number_length" class="form-label">
                                                    <i class="ri-ruler-line"></i>Tracking Number Length
                                                </label>
                                                <input type="number" class="form-control" id="tracking_number_length" name="tracking_number_length" 
                                                       value="<?php echo getSetting($settings, 'shipping', 'tracking_number_length', '10'); ?>" min="6" max="20">
                                                <div class="form-text">Total length including prefix</div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="manifest_number_prefix" class="form-label">
                                                    <i class="ri-file-list-3-line"></i>Manifest Number Prefix
                                                </label>
                                                <input type="text" class="form-control" id="manifest_number_prefix" name="manifest_number_prefix" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'shipping', 'manifest_number_prefix', 'MAN')); ?>" maxlength="5">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="default_weight_unit" class="form-label">
                                                    <i class="ri-scales-line"></i>Default Weight Unit
                                                </label>
                                                <select class="form-control" id="default_weight_unit" name="default_weight_unit">
                                                    <option value="KG" <?php echo getSetting($settings, 'shipping', 'default_weight_unit', 'KG') == 'KG' ? 'selected' : ''; ?>>Kilograms (KG)</option>
                                                    <option value="LB" <?php echo getSetting($settings, 'shipping', 'default_weight_unit') == 'LB' ? 'selected' : ''; ?>>Pounds (LB)</option>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="default_dimension_unit" class="form-label">
                                                    <i class="ri-ruler-2-line"></i>Default Dimension Unit
                                                </label>
                                                <select class="form-control" id="default_dimension_unit" name="default_dimension_unit">
                                                    <option value="CM" <?php echo getSetting($settings, 'shipping', 'default_dimension_unit', 'CM') == 'CM' ? 'selected' : ''; ?>>Centimeters (CM)</option>
                                                    <option value="IN" <?php echo getSetting($settings, 'shipping', 'default_dimension_unit') == 'IN' ? 'selected' : ''; ?>>Inches (IN)</option>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="volumetric_factor" class="form-label">
                                                    <i class="ri-cube-line"></i>Volumetric Weight Factor
                                                </label>
                                                <input type="number" class="form-control" id="volumetric_factor" name="volumetric_factor" 
                                                       value="<?php echo getSetting($settings, 'shipping', 'volumetric_factor', '5000'); ?>" min="1000" max="10000">
                                                <div class="form-text">Factor used to calculate volumetric weight (L×W×H÷factor)</div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="pickup_cutoff_time" class="form-label">
                                                    <i class="ri-time-line"></i>Daily Pickup Cutoff Time
                                                </label>
                                                <input type="time" class="form-control" id="pickup_cutoff_time" name="pickup_cutoff_time" 
                                                       value="<?php echo getSetting($settings, 'shipping', 'pickup_cutoff_time', '15:00'); ?>">
                                                <div class="form-text">Latest time for same-day pickup requests</div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="delivery_attempt_limit" class="form-label">
                                                    <i class="ri-repeat-line"></i>Maximum Delivery Attempts
                                                </label>
                                                <input type="number" class="form-control" id="delivery_attempt_limit" name="delivery_attempt_limit" 
                                                       value="<?php echo getSetting($settings, 'shipping', 'delivery_attempt_limit', '3'); ?>" min="1" max="10">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-shield-check-line"></i>Proof of Delivery Required
                                                </label>
                                                <div class="d-flex align-items-center">
                                                    <label class="toggle-switch">
                                                        <input type="checkbox" name="proof_of_delivery_required" value="1" 
                                                               <?php echo getSetting($settings, 'delivery', 'proof_of_delivery_required', '1') == '1' ? 'checked' : ''; ?>>
                                                        <span class="toggle-slider"></span>
                                                    </label>
                                                    <span class="ms-3">Require proof of delivery for all shipments</span>
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-customs-line"></i>Customs Clearance Tracking
                                                </label>
                                                <div class="d-flex align-items-center">
                                                    <label class="toggle-switch">
                                                        <input type="checkbox" name="customs_clearance_required" value="1" 
                                                               <?php echo getSetting($settings, 'customs', 'customs_clearance_required', '1') == '1' ? 'checked' : ''; ?>>
                                                        <span class="toggle-slider"></span>
                                                    </label>
                                                    <span class="ms-3">Enable customs clearance tracking</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Email Settings -->
                            <div class="tab-pane fade" id="email" role="tabpanel">
                                <div class="settings-card">
                                    <div class="settings-tab-header">
                                        <h5 class="settings-tab-title">
                                            <i class="ri-mail-line"></i>Email Configuration
                                        </h5>
                                    </div>
                                    <div class="settings-form-section">
                                        <div class="settings-grid">
                                            <div class="form-group">
                                                <label for="smtp_host" class="form-label">
                                                    <i class="ri-server-line"></i>SMTP Host
                                                </label>
                                                <input type="text" class="form-control" id="smtp_host" name="smtp_host" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'email', 'smtp_host', 'smtp.example.com')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="smtp_port" class="form-label">
                                                    <i class="ri-plug-line"></i>SMTP Port
                                                </label>
                                                <input type="number" class="form-control" id="smtp_port" name="smtp_port" 
                                                       value="<?php echo getSetting($settings, 'email', 'smtp_port', '587'); ?>" min="1" max="65535">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="smtp_security" class="form-label">
                                                    <i class="ri-shield-line"></i>SMTP Security
                                                </label>
                                                <select class="form-control" id="smtp_security" name="smtp_security">
                                                    <option value="none" <?php echo getSetting($settings, 'email', 'smtp_security') == 'none' ? 'selected' : ''; ?>>None</option>
                                                    <option value="ssl" <?php echo getSetting($settings, 'email', 'smtp_security') == 'ssl' ? 'selected' : ''; ?>>SSL</option>
                                                    <option value="tls" <?php echo getSetting($settings, 'email', 'smtp_security', 'tls') == 'tls' ? 'selected' : ''; ?>>TLS</option>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="smtp_username" class="form-label">
                                                    <i class="ri-user-line"></i>SMTP Username
                                                </label>
                                                <input type="text" class="form-control" id="smtp_username" name="smtp_username" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'email', 'smtp_username', 'user@example.com')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="smtp_password" class="form-label">
                                                    <i class="ri-lock-line"></i>SMTP Password
                                                </label>
                                                <input type="password" class="form-control" id="smtp_password" name="smtp_password" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'email', 'smtp_password', '')); ?>" placeholder="Enter password">
                                                <div class="form-text">Leave blank to keep existing password</div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="email_from_name" class="form-label">
                                                    <i class="ri-user-heart-line"></i>From Name
                                                </label>
                                                <input type="text" class="form-control" id="email_from_name" name="email_from_name" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'email', 'email_from_name', 'Freight System')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="email_from_address" class="form-label">
                                                    <i class="ri-mail-send-line"></i>From Email Address
                                                </label>
                                                <input type="email" class="form-control" id="email_from_address" name="email_from_address" 
                                                       value="<?php echo htmlspecialchars(getSetting($settings, 'email', 'email_from_address', 'freight@polakis.co.ke')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="email_signature" class="form-label">
                                                    <i class="ri-file-text-line"></i>Email Signature
                                                </label>
                                                <textarea class="form-control" id="email_signature" name="email_signature" rows="3"><?php echo htmlspecialchars(getSetting($settings, 'email', 'email_signature', "Regards,\nFreight Department")); ?></textarea>
                                            </div>
                                        </div>
                                        
                                        <div class="mt-4">
                                            <button type="button" class="btn btn-outline-primary" onclick="testEmailConfiguration()">
                                                <i class="ri-mail-check-line me-2"></i>Test Email Configuration
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Save Button -->
                        <button type="submit" class="save-button" id="saveButton">
                            <i class="ri-save-line me-2"></i>Save Settings
                        </button>
                    </form>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Auto-save draft functionality
    let autoSaveTimer;
    let hasUnsavedChanges = false;
    
    // Track changes
    $('input, select, textarea').on('change input', function() {
        hasUnsavedChanges = true;
        clearTimeout(autoSaveTimer);
        autoSaveTimer = setTimeout(function() {
            saveDraft();
        }, 2000);
    });
    
    // Form submission
    $('#settingsForm').on('submit', function(e) {
        e.preventDefault();
        saveSettings();
    });
    
    // Warn about unsaved changes
    window.addEventListener('beforeunload', function(e) {
        if (hasUnsavedChanges) {
            e.preventDefault();
            e.returnValue = '';
        }
    });
    
    // Keyboard shortcuts
    $(document).on('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            saveSettings();
        }
    });
    
    // Initialize currency preview
    updateCurrencyPreview();
});

function saveSettings() {
    const formData = new FormData($('#settingsForm')[0]);
    
    // Handle checkboxes - ensure unchecked boxes send 0
    $('input[type="checkbox"]').each(function() {
        if (!this.checked) {
            formData.set(this.name, '0');
        }
    });
    
    // Show loading
    Swal.fire({
        title: 'Saving Settings...',
        text: 'Please wait while we save your configuration.',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'system_settings.php',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                hasUnsavedChanges = false;
                localStorage.removeItem('settings_draft'); // Clear draft
                Swal.fire({
                    title: 'Settings Saved!',
                    text: response.message,
                    icon: 'success',
                    timer: 3000,
                    showConfirmButton: false
                }).then(() => {
                    // Optionally reload to show updated values
                   // location.reload();
                });
            } else {
                Swal.fire({
                    title: 'Error',
                    text: response.message,
                    icon: 'error'
                });
            }
        },
        error: function(xhr, status, error) {
            console.error('Save error:', error);
            console.error('Response:', xhr.responseText);
            Swal.fire({
                title: 'Error',
                text: 'An error occurred while saving settings. Please check the console.',
                icon: 'error'
            });
        }
    });
}

function saveDraft() {
    const formData = {};
    $('#settingsForm').serializeArray().forEach(function(item) {
        formData[item.name] = item.value;
    });
    localStorage.setItem('settings_draft', JSON.stringify(formData));
    
    const saveButton = $('#saveButton');
    const originalText = saveButton.html();
    saveButton.html('<i class="ri-draft-line me-2"></i>Draft Saved');
    setTimeout(() => {
        saveButton.html(originalText);
    }, 2000);
}

function updateCurrencyPreview() {
    const currency = $('#default_currency').val();
    const symbol = $('#currency_symbol').val();
    const position = $('#currency_position').val();
    const decimals = parseInt($('#decimal_places').val() || 2);
    
    const amount = (1234.56).toFixed(decimals);
    let preview = '';
    
    if (position === 'before') {
        preview = symbol + ' ' + amount;
    } else {
        preview = amount + ' ' + symbol;
    }
    
    $('#currencyPreviewAmount').text(preview);
}

function testEmailConfiguration() {
    const emailData = {
        smtp_host: $('#smtp_host').val(),
        smtp_port: $('#smtp_port').val(),
        smtp_security: $('#smtp_security').val(),
        smtp_username: $('#smtp_username').val(),
        smtp_password: $('#smtp_password').val(),
        email_from_address: $('#email_from_address').val(),
        email_from_name: $('#email_from_name').val()
    };
    
    if (!emailData.smtp_host || !emailData.smtp_port || !emailData.email_from_address) {
        Swal.fire({
            title: 'Missing Information',
            text: 'Please fill in SMTP host, port, and from email address before testing.',
            icon: 'warning'
        });
        return;
    }
    
    Swal.fire({
        title: 'Testing Email Configuration...',
        text: 'Please wait while we test your email settings.',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
            
            setTimeout(() => {
                Swal.fire({
                    title: 'Email Test Successful!',
                    text: 'Your email configuration is working correctly.',
                    icon: 'success',
                    confirmButtonText: 'Great!'
                });
            }, 3000);
        }
    });
}

// Currency field updates
$('#default_currency').on('change', function() {
    const currencySymbols = {
        'KES': 'KSh',
        'USD': '$',
        'EUR': '€',
        'GBP': '£',
        'UGX': 'USh',
        'TZS': 'TSh',
        'RWF': 'RF'
    };
    
    const selectedCurrency = $(this).val();
    if (currencySymbols[selectedCurrency]) {
        $('#currency_symbol').val(currencySymbols[selectedCurrency]);
    }
    updateCurrencyPreview();
});

$('#currency_symbol, #currency_position, #decimal_places').on('change input', function() {
    updateCurrencyPreview();
});

// Tab persistence
$('a[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
    localStorage.setItem('activeSettingsTab', e.target.getAttribute('href'));
});

// Restore active tab on page load
const activeTab = localStorage.getItem('activeSettingsTab');
if (activeTab) {
    $('a[href="' + activeTab + '"]').tab('show');
}

// Load draft on page load
const draft = localStorage.getItem('settings_draft');
if (draft && confirm('Do you want to restore your unsaved changes?')) {
    const formData = JSON.parse(draft);
    Object.keys(formData).forEach(function(key) {
        const field = $('[name="' + key + '"]');
        if (field.length) {
            if (field.is(':checkbox')) {
                field.prop('checked', formData[key] === '1');
            } else {
                field.val(formData[key]);
            }
        }
    });
    hasUnsavedChanges = true;
    updateCurrencyPreview();
}
</script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>