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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is admin
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Super Admin') {
    header('Location: index.php');
    exit();
}

// Check if system_settings table exists, if not create it
$table_check = $conn->query("SHOW TABLES LIKE 'system_settings'");
if ($table_check->num_rows === 0) {
    // Table doesn't exist, create it
    $create_table_sql = "
    CREATE TABLE IF NOT EXISTS `system_settings` (
      `id` int NOT NULL AUTO_INCREMENT,
      `setting_key` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
      `setting_value` text COLLATE utf8mb4_unicode_ci,
      `setting_type` enum('text','number','boolean','json') COLLATE utf8mb4_unicode_ci DEFAULT 'text',
      `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
      `is_public` tinyint(1) DEFAULT '0',
      `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
      `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `setting_key` (`setting_key`),
      KEY `idx_setting_key` (`setting_key`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    ";
    
    if ($conn->query($create_table_sql)) {
        // Insert default settings
        $default_settings = [
            ['company_name', 'Property Management System', 'text', 'Company name', 1],
            ['company_email', 'info@property.co.ke', 'text', 'Company email', 1],
            ['company_phone', '+254712345678', 'text', 'Company phone', 1],
            ['company_address', 'Nairobi, Kenya', 'text', 'Company address', 1],
            ['company_logo', 'assets/images/logo.png', 'text', 'Company logo path', 1],
            ['system_timezone', 'Africa/Nairobi', 'text', 'System timezone', 0],
            ['currency', 'KES', 'text', 'Currency code', 1],
            ['currency_symbol', 'KSh', 'text', 'Currency symbol', 1],
            ['default_payment_method', 'M-Pesa', 'text', 'Default payment method', 0],
            ['mpesa_enabled', '0', 'boolean', 'Enable M-Pesa', 0],
            ['mpesa_environment', 'sandbox', 'text', 'M-Pesa environment', 0],
            ['mpesa_shortcode', '174379', 'text', 'M-Pesa shortcode', 0],
            ['mpesa_consumer_key', '', 'text', 'M-Pesa consumer key', 0],
            ['mpesa_consumer_secret', '', 'text', 'M-Pesa consumer secret', 0],
            ['mpesa_passkey', '', 'text', 'M-Pesa passkey', 0],
            ['enable_email_notifications', '1', 'boolean', 'Enable email notifications', 0],
            ['enable_sms_notifications', '1', 'boolean', 'Enable SMS notifications', 0],
            ['invoice_prefix', 'INV', 'text', 'Invoice number prefix', 0],
            ['vat_enabled', '1', 'boolean', 'Enable VAT', 0],
            ['vat_rate', '16', 'number', 'VAT rate percentage', 0]
        ];
        
        $insert_stmt = $conn->prepare(
            "INSERT INTO system_settings (setting_key, setting_value, setting_type, description, is_public) 
             VALUES (?, ?, ?, ?, ?) 
             ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)"
        );
        
        foreach ($default_settings as $setting) {
            $insert_stmt->bind_param("ssssi", 
                $setting[0], $setting[1], $setting[2], $setting[3], $setting[4]
            );
            $insert_stmt->execute();
        }
        
        $_SESSION['success_message'] = "System settings table created successfully!";
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Handle settings update
    $settings = $_POST['settings'] ?? [];
    
    $success_count = 0;
    $error_count = 0;
    
    foreach ($settings as $key => $value) {
        // Handle checkbox values
        if (!isset($_POST['settings'][$key]) && 
            (strpos($key, 'enable_') === 0 || strpos($key, 'mpesa_enabled') !== false)) {
            $value = '0';
        }
        
        $sql = "INSERT INTO system_settings (setting_key, setting_value, updated_at) 
                VALUES (?, ?, NOW())
                ON DUPLICATE KEY UPDATE setting_value = ?, updated_at = NOW()";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sss", $key, $value, $value);
        
        if ($stmt->execute()) {
            $success_count++;
        } else {
            $error_count++;
        }
    }
    
    if ($error_count == 0) {
        $_SESSION['success_message'] = "All settings updated successfully! ($success_count settings)";
    } else {
        $_SESSION['error_message'] = "Some settings failed to update. Success: $success_count, Failed: $error_count";
    }
    
    header('Location: system_settings.php');
    exit();
}

// Get current settings
$settings = [];
try {
    $sql_settings = "SELECT setting_key, setting_value FROM system_settings";
    $result_settings = $conn->query($sql_settings);
    
    if ($result_settings) {
        while($row = $result_settings->fetch_assoc()) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
    }
} catch (Exception $e) {
    $_SESSION['error_message'] = "Error loading settings: " . $e->getMessage();
}

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

// Helper function to check if setting is enabled
function isSettingEnabled($settings, $key) {
    return ($settings[$key] ?? '0') == '1';
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'System Settings')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .settings-section {
            margin-bottom: 2rem;
            padding-bottom: 2rem;
            border-bottom: 1px solid #e9ecef;
        }
        
        .settings-section:last-child {
            border-bottom: none;
        }
        
        .settings-section h5 {
            color: #495057;
            font-weight: 600;
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #0d6efd;
            display: inline-block;
        }
        
        .form-label {
            font-weight: 500;
            color: #495057;
        }
        
        .form-text {
            font-size: 0.875rem;
            color: #6c757d;
        }
        
        .settings-card {
            box-shadow: 0 0 20px rgba(0,0,0,0.05);
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System', 'title' => 'System Settings')); ?>

                    <!-- Success/Error Messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="ri-checkbox-circle-line me-2"></i>
                            <?php 
                                echo $_SESSION['success_message']; 
                                unset($_SESSION['success_message']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="ri-error-warning-line me-2"></i>
                            <?php 
                                echo $_SESSION['error_message']; 
                                unset($_SESSION['error_message']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card settings-card">
                                <div class="card-header bg-primary">
                                    <h4 class="card-title mb-0 text-white">
                                        <i class="ri-settings-3-line me-2"></i>System Configuration
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <form method="POST" id="settingsForm">
                                        
                                        <!-- Company Information Section -->
                                        <div class="settings-section">
                                            <h5><i class="ri-building-line me-2"></i>Company Information</h5>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Company Name <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" name="settings[company_name]" 
                                                           value="<?php echo getSetting($settings, 'company_name'); ?>"
                                                           required>
                                                    <small class="form-text">This will appear on invoices and reports</small>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Company Email <span class="text-danger">*</span></label>
                                                    <input type="email" class="form-control" name="settings[company_email]" 
                                                           value="<?php echo getSetting($settings, 'company_email'); ?>"
                                                           required>
                                                    <small class="form-text">Official email address</small>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Company Phone</label>
                                                    <input type="text" class="form-control" name="settings[company_phone]" 
                                                           value="<?php echo getSetting($settings, 'company_phone', '+254'); ?>"
                                                           placeholder="+254712345678">
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Company Address</label>
                                                    <input type="text" class="form-control" name="settings[company_address]" 
                                                           value="<?php echo getSetting($settings, 'company_address'); ?>"
                                                           placeholder="Nairobi, Kenya">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Currency & Localization Section -->
                                        <div class="settings-section">
                                            <h5><i class="ri-money-dollar-circle-line me-2"></i>Currency & Localization</h5>
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Currency Code</label>
                                                    <input type="text" class="form-control" name="settings[currency]" 
                                                           value="<?php echo getSetting($settings, 'currency', 'KES'); ?>"
                                                           placeholder="KES">
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Currency Symbol</label>
                                                    <input type="text" class="form-control" name="settings[currency_symbol]" 
                                                           value="<?php echo getSetting($settings, 'currency_symbol', 'KSh'); ?>"
                                                           placeholder="KSh">
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Timezone</label>
                                                    <select class="form-select" name="settings[system_timezone]">
                                                        <option value="Africa/Nairobi" <?php echo getSetting($settings, 'system_timezone', 'Africa/Nairobi') == 'Africa/Nairobi' ? 'selected' : ''; ?>>East Africa Time (Nairobi)</option>
                                                        <option value="Africa/Johannesburg" <?php echo getSetting($settings, 'system_timezone') == 'Africa/Johannesburg' ? 'selected' : ''; ?>>South Africa Time</option>
                                                        <option value="UTC" <?php echo getSetting($settings, 'system_timezone') == 'UTC' ? 'selected' : ''; ?>>UTC</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Payment Settings Section -->
                                        <div class="settings-section">
                                            <h5><i class="ri-bank-card-line me-2"></i>Payment Settings</h5>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Default Payment Method</label>
                                                    <select class="form-select" name="settings[default_payment_method]">
                                                        <option value="M-Pesa" <?php echo getSetting($settings, 'default_payment_method', 'M-Pesa') == 'M-Pesa' ? 'selected' : ''; ?>>M-Pesa</option>
                                                        <option value="Bank Transfer" <?php echo getSetting($settings, 'default_payment_method') == 'Bank Transfer' ? 'selected' : ''; ?>>Bank Transfer</option>
                                                        <option value="Cash" <?php echo getSetting($settings, 'default_payment_method') == 'Cash' ? 'selected' : ''; ?>>Cash</option>
                                                        <option value="Cheque" <?php echo getSetting($settings, 'default_payment_method') == 'Cheque' ? 'selected' : ''; ?>>Cheque</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Invoice Prefix</label>
                                                    <input type="text" class="form-control" name="settings[invoice_prefix]" 
                                                           value="<?php echo getSetting($settings, 'invoice_prefix', 'INV'); ?>"
                                                           placeholder="INV">
                                                    <small class="form-text">E.g., INV-2025-001</small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- M-Pesa Integration Section -->
                                        <div class="settings-section">
                                            <h5><i class="ri-phone-line me-2"></i>M-Pesa Integration</h5>
                                            <div class="row">
                                                <div class="col-md-12 mb-3">
                                                    <div class="alert alert-info">
                                                        <i class="ri-information-line me-2"></i>
                                                        <strong>M-Pesa STK Push Setup:</strong> Get your credentials from the 
                                                        <a href="https://developer.safaricom.co.ke/" target="_blank">Safaricom Daraja Portal</a>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-12 mb-3">
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" id="mpesaEnabled"
                                                               name="settings[mpesa_enabled]" value="1" 
                                                               <?php echo isSettingEnabled($settings, 'mpesa_enabled') ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="mpesaEnabled">
                                                            Enable M-Pesa STK Push
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div id="mpesaSettings" style="<?php echo !isSettingEnabled($settings, 'mpesa_enabled') ? 'display:none;' : ''; ?>">
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label">Environment</label>
                                                        <select class="form-select" name="settings[mpesa_environment]">
                                                            <option value="sandbox" <?php echo getSetting($settings, 'mpesa_environment', 'sandbox') == 'sandbox' ? 'selected' : ''; ?>>Sandbox (Testing)</option>
                                                            <option value="production" <?php echo getSetting($settings, 'mpesa_environment') == 'production' ? 'selected' : ''; ?>>Production (Live)</option>
                                                        </select>
                                                        <small class="form-text">Use sandbox for testing</small>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label">Business Shortcode <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control" name="settings[mpesa_shortcode]" 
                                                               value="<?php echo getSetting($settings, 'mpesa_shortcode', '174379'); ?>" 
                                                               placeholder="e.g., 174379">
                                                        <small class="form-text">Your M-Pesa till or paybill number</small>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label">Consumer Key <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control" name="settings[mpesa_consumer_key]" 
                                                               value="<?php echo getSetting($settings, 'mpesa_consumer_key'); ?>" 
                                                               placeholder="Your M-Pesa Consumer Key">
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label">Consumer Secret <span class="text-danger">*</span></label>
                                                        <input type="password" class="form-control" name="settings[mpesa_consumer_secret]" 
                                                               value="<?php echo getSetting($settings, 'mpesa_consumer_secret'); ?>" 
                                                               placeholder="Your M-Pesa Consumer Secret">
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-12 mb-3">
                                                        <label class="form-label">Passkey <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control" name="settings[mpesa_passkey]" 
                                                               value="<?php echo getSetting($settings, 'mpesa_passkey'); ?>" 
                                                               placeholder="Your M-Pesa Passkey">
                                                        <small class="form-text">Get this from your M-Pesa Developer Portal under "Lipa Na M-Pesa Online"</small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Notification Settings Section -->
                                        <div class="settings-section">
                                            <h5><i class="ri-notification-line me-2"></i>Notification Settings</h5>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" id="emailNotif"
                                                               name="settings[enable_email_notifications]" value="1" 
                                                               <?php echo isSettingEnabled($settings, 'enable_email_notifications') ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="emailNotif">
                                                            Enable Email Notifications
                                                        </label>
                                                    </div>
                                                    <small class="form-text d-block mt-2">Send invoice, payment, and reminder emails</small>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" id="smsNotif"
                                                               name="settings[enable_sms_notifications]" value="1" 
                                                               <?php echo isSettingEnabled($settings, 'enable_sms_notifications') ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="smsNotif">
                                                            Enable SMS Notifications
                                                        </label>
                                                    </div>
                                                    <small class="form-text d-block mt-2">Send SMS for important updates</small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Tax Settings Section -->
                                        <div class="settings-section">
                                            <h5><i class="ri-percent-line me-2"></i>Tax Settings</h5>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check form-switch mb-3">
                                                        <input class="form-check-input" type="checkbox" id="vatEnabled"
                                                               name="settings[vat_enabled]" value="1" 
                                                               <?php echo isSettingEnabled($settings, 'vat_enabled') ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="vatEnabled">
                                                            Enable VAT
                                                        </label>
                                                    </div>
                                                    <label class="form-label">VAT Rate (%)</label>
                                                    <input type="number" class="form-control" name="settings[vat_rate]" 
                                                           value="<?php echo getSetting($settings, 'vat_rate', '16'); ?>" 
                                                           step="0.01" min="0" max="100"
                                                           placeholder="16">
                                                    <small class="form-text">Kenya standard VAT rate is 16%</small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Form Actions -->
                                        <div class="mt-4 pt-3 border-top">
                                            <button type="submit" class="btn btn-primary btn-lg">
                                                <i class="ri-save-line align-bottom me-1"></i>Save All Settings
                                            </button>
                                            <button type="reset" class="btn btn-secondary btn-lg ms-2">
                                                <i class="ri-refresh-line align-bottom me-1"></i>Reset Form
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Toggle M-Pesa settings visibility
        document.getElementById('mpesaEnabled')?.addEventListener('change', function() {
            const mpesaSettings = document.getElementById('mpesaSettings');
            if (this.checked) {
                mpesaSettings.style.display = 'block';
            } else {
                mpesaSettings.style.display = 'none';
            }
        });

        // Form validation
        document.getElementById('settingsForm')?.addEventListener('submit', function(e) {
            const mpesaEnabled = document.getElementById('mpesaEnabled').checked;
            
            if (mpesaEnabled) {
                const shortcode = document.querySelector('[name="settings[mpesa_shortcode]"]').value;
                const consumerKey = document.querySelector('[name="settings[mpesa_consumer_key]"]').value;
                const consumerSecret = document.querySelector('[name="settings[mpesa_consumer_secret]"]').value;
                const passkey = document.querySelector('[name="settings[mpesa_passkey]"]').value;
                
                if (!shortcode || !consumerKey || !consumerSecret || !passkey) {
                    e.preventDefault();
                    alert('Please fill in all required M-Pesa fields when M-Pesa is enabled.');
                    return false;
                }
            }
        });

        // Auto-dismiss alerts after 5 seconds
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 5000);
    </script>
</body>
</html>