<?php
require_once 'config/database.php';
requireAdmin();

require_once 'templates/header.php';
require_once 'templates/navbar.php';
require_once 'templates/sidebar.php';
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">System Settings</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item active">System Settings</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-3">
                    <!-- Settings Navigation -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Settings Categories</h3>
                        </div>
                        <div class="card-body p-0">
                            <nav class="nav nav-pills nav-sidebar flex-column" id="settingsNav">
                                <a class="nav-link active" href="#general" data-toggle="tab">
                                    <i class="fas fa-cog"></i> General Settings
                                </a>
                                <a class="nav-link" href="#organization" data-toggle="tab">
                                    <i class="fas fa-building"></i> Organization Info
                                </a>
                                <a class="nav-link" href="#email" data-toggle="tab">
                                    <i class="fas fa-envelope"></i> Email Configuration
                                </a>
                                <a class="nav-link" href="#security" data-toggle="tab">
                                    <i class="fas fa-shield-alt"></i> Security Settings
                                </a>
                                <a class="nav-link" href="#membership" data-toggle="tab">
                                    <i class="fas fa-users"></i> Membership Settings
                                </a>
                                <a class="nav-link" href="#notifications" data-toggle="tab">
                                    <i class="fas fa-bell"></i> Notifications
                                </a>
                                <a class="nav-link" href="#backup" data-toggle="tab">
                                    <i class="fas fa-database"></i> Backup & Recovery
                                </a>
                                <a class="nav-link" href="#integrations" data-toggle="tab">
                                    <i class="fas fa-plug"></i> Integrations
                                </a>
                            </nav>
                        </div>
                    </div>
                </div>

                <div class="col-md-9">
                    <div class="tab-content">
                        <!-- General Settings -->
                        <div class="tab-pane fade show active" id="general">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">General Settings</h3>
                                </div>
                                <form id="generalSettingsForm">
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Site Title</label>
                                                    <input type="text" class="form-control" name="site_title" value="KSO Chandigarh">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Site Description</label>
                                                    <input type="text" class="form-control" name="site_description" value="Khalsa Sports Organization">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Date Format</label>
                                                    <select class="form-control" name="date_format">
                                                        <option value="Y-m-d">YYYY-MM-DD</option>
                                                        <option value="d/m/Y">DD/MM/YYYY</option>
                                                        <option value="m/d/Y">MM/DD/YYYY</option>
                                                        <option value="d-m-Y">DD-MM-YYYY</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Time Format</label>
                                                    <select class="form-control" name="time_format">
                                                        <option value="H:i">24 Hour</option>
                                                        <option value="h:i A">12 Hour</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Currency</label>
                                                    <select class="form-control" name="currency">
                                                        <option value="INR">Indian Rupee (₹)</option>
                                                        <option value="USD">US Dollar ($)</option>
                                                        <option value="EUR">Euro (€)</option>
                                                        <option value="GBP">British Pound (£)</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Language</label>
                                                    <select class="form-control" name="language">
                                                        <option value="en">English</option>
                                                        <option value="hi">Hindi</option>
                                                        <option value="pa">Punjabi</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="maintenance_mode" name="maintenance_mode">
                                                <label class="custom-control-label" for="maintenance_mode">Maintenance Mode</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-footer">
                                        <button type="submit" class="btn btn-primary">Save General Settings</button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Organization Info -->
                        <div class="tab-pane fade" id="organization">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Organization Information</h3>
                                </div>
                                <form id="organizationForm">
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Organization Name</label>
                                                    <input type="text" class="form-control" name="org_name" value="Khalsa Sports Organization">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Registration Number</label>
                                                    <input type="text" class="form-control" name="registration_number">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label>Address</label>
                                            <textarea class="form-control" name="address" rows="3"></textarea>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label>City</label>
                                                    <input type="text" class="form-control" name="city" value="Chandigarh">
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label>State</label>
                                                    <input type="text" class="form-control" name="state" value="Chandigarh">
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label>Postal Code</label>
                                                    <input type="text" class="form-control" name="postal_code">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Phone</label>
                                                    <input type="text" class="form-control" name="phone">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Email</label>
                                                    <input type="email" class="form-control" name="email">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Website</label>
                                                    <input type="url" class="form-control" name="website">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Logo Upload</label>
                                                    <input type="file" class="form-control" name="logo" accept="image/*">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-footer">
                                        <button type="submit" class="btn btn-primary">Save Organization Info</button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Email Configuration -->
                        <div class="tab-pane fade" id="email">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Email Configuration</h3>
                                </div>
                                <form id="emailConfigForm">
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>SMTP Host</label>
                                                    <input type="text" class="form-control" name="smtp_host">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>SMTP Port</label>
                                                    <input type="number" class="form-control" name="smtp_port" value="587">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>SMTP Username</label>
                                                    <input type="text" class="form-control" name="smtp_username">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>SMTP Password</label>
                                                    <input type="password" class="form-control" name="smtp_password">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>From Email</label>
                                                    <input type="email" class="form-control" name="from_email">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>From Name</label>
                                                    <input type="text" class="form-control" name="from_name">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label>Email Encryption</label>
                                            <select class="form-control" name="smtp_encryption">
                                                <option value="tls">TLS</option>
                                                <option value="ssl">SSL</option>
                                                <option value="">None</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <button type="button" class="btn btn-info" onclick="testEmail()">
                                                <i class="fas fa-paper-plane"></i> Test Email Configuration
                                            </button>
                                        </div>
                                    </div>
                                    <div class="card-footer">
                                        <button type="submit" class="btn btn-primary">Save Email Configuration</button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Security Settings -->
                        <div class="tab-pane fade" id="security">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Security Settings</h3>
                                </div>
                                <form id="securitySettingsForm">
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Session Timeout (minutes)</label>
                                                    <input type="number" class="form-control" name="session_timeout" value="30">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Password Expiry (days)</label>
                                                    <input type="number" class="form-control" name="password_expiry" value="90">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Max Login Attempts</label>
                                                    <input type="number" class="form-control" name="max_login_attempts" value="5">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Account Lockout Duration (minutes)</label>
                                                    <input type="number" class="form-control" name="lockout_duration" value="15">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="two_factor_auth" name="two_factor_auth">
                                                <label class="custom-control-label" for="two_factor_auth">Enable Two-Factor Authentication</label>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="ip_whitelist" name="ip_whitelist">
                                                <label class="custom-control-label" for="ip_whitelist">Enable IP Whitelist</label>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="audit_logging" name="audit_logging" checked>
                                                <label class="custom-control-label" for="audit_logging">Enable Audit Logging</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-footer">
                                        <button type="submit" class="btn btn-primary">Save Security Settings</button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Membership Settings -->
                        <div class="tab-pane fade" id="membership">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Membership Settings</h3>
                                </div>
                                <form id="membershipSettingsForm">
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Membership ID Prefix</label>
                                                    <input type="text" class="form-control" name="member_id_prefix" value="KSO">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Auto-generate Member ID</label>
                                                    <select class="form-control" name="auto_generate_id">
                                                        <option value="1">Yes</option>
                                                        <option value="0">No</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Default Membership Duration (months)</label>
                                                    <input type="number" class="form-control" name="default_duration" value="12">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Renewal Reminder (days before expiry)</label>
                                                    <input type="number" class="form-control" name="renewal_reminder" value="30">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="require_approval" name="require_approval">
                                                <label class="custom-control-label" for="require_approval">Require Admin Approval for New Members</label>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="auto_id_card" name="auto_id_card" checked>
                                                <label class="custom-control-label" for="auto_id_card">Auto-generate ID Card on Approval</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-footer">
                                        <button type="submit" class="btn btn-primary">Save Membership Settings</button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Notifications -->
                        <div class="tab-pane fade" id="notifications">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Notification Settings</h3>
                                </div>
                                <form id="notificationSettingsForm">
                                    <div class="card-body">
                                        <h5>Email Notifications</h5>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="email_new_member" name="email_new_member" checked>
                                                <label class="custom-control-label" for="email_new_member">New Member Registration</label>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="email_membership_expiry" name="email_membership_expiry" checked>
                                                <label class="custom-control-label" for="email_membership_expiry">Membership Expiry</label>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="email_event_reminder" name="email_event_reminder" checked>
                                                <label class="custom-control-label" for="email_event_reminder">Event Reminders</label>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="email_payment_received" name="email_payment_received" checked>
                                                <label class="custom-control-label" for="email_payment_received">Payment Received</label>
                                            </div>
                                        </div>
                                        
                                        <hr>
                                        
                                        <h5>SMS Notifications</h5>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="sms_enabled" name="sms_enabled">
                                                <label class="custom-control-label" for="sms_enabled">Enable SMS Notifications</label>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>SMS API Key</label>
                                                    <input type="text" class="form-control" name="sms_api_key">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>SMS Sender ID</label>
                                                    <input type="text" class="form-control" name="sms_sender_id">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-footer">
                                        <button type="submit" class="btn btn-primary">Save Notification Settings</button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Backup & Recovery -->
                        <div class="tab-pane fade" id="backup">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Backup & Recovery</h3>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h5>Database Backup</h5>
                                            <p>Create a backup of your database</p>
                                            <button type="button" class="btn btn-primary" onclick="createBackup()">
                                                <i class="fas fa-download"></i> Create Backup
                                            </button>
                                        </div>
                                        <div class="col-md-6">
                                            <h5>Restore Database</h5>
                                            <p>Restore from a backup file</p>
                                            <input type="file" class="form-control mb-2" id="restoreFile" accept=".sql">
                                            <button type="button" class="btn btn-warning" onclick="restoreBackup()">
                                                <i class="fas fa-upload"></i> Restore Backup
                                            </button>
                                        </div>
                                    </div>
                                    <hr>
                                    <h5>Auto Backup Settings</h5>
                                    <form id="autoBackupForm">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <div class="custom-control custom-switch">
                                                        <input type="checkbox" class="custom-control-input" id="auto_backup" name="auto_backup">
                                                        <label class="custom-control-label" for="auto_backup">Enable Auto Backup</label>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Backup Frequency</label>
                                                    <select class="form-control" name="backup_frequency">
                                                        <option value="daily">Daily</option>
                                                        <option value="weekly">Weekly</option>
                                                        <option value="monthly">Monthly</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <button type="submit" class="btn btn-primary">Save Backup Settings</button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Integrations -->
                        <div class="tab-pane fade" id="integrations">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Third-Party Integrations</h3>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h5>Payment Gateway</h5>
                                            <form id="paymentIntegrationForm">
                                                <div class="form-group">
                                                    <label>Payment Gateway</label>
                                                    <select class="form-control" name="payment_gateway">
                                                        <option value="">Select Gateway</option>
                                                        <option value="razorpay">Razorpay</option>
                                                        <option value="paytm">Paytm</option>
                                                        <option value="paypal">PayPal</option>
                                                        <option value="stripe">Stripe</option>
                                                    </select>
                                                </div>
                                                <div class="form-group">
                                                    <label>API Key</label>
                                                    <input type="text" class="form-control" name="payment_api_key">
                                                </div>
                                                <div class="form-group">
                                                    <label>API Secret</label>
                                                    <input type="password" class="form-control" name="payment_api_secret">
                                                </div>
                                                <button type="submit" class="btn btn-primary">Save Payment Settings</button>
                                            </form>
                                        </div>
                                        <div class="col-md-6">
                                            <h5>Social Media</h5>
                                            <form id="socialMediaForm">
                                                <div class="form-group">
                                                    <label>Facebook Page URL</label>
                                                    <input type="url" class="form-control" name="facebook_url">
                                                </div>
                                                <div class="form-group">
                                                    <label>Instagram URL</label>
                                                    <input type="url" class="form-control" name="instagram_url">
                                                </div>
                                                <div class="form-group">
                                                    <label>Twitter URL</label>
                                                    <input type="url" class="form-control" name="twitter_url">
                                                </div>
                                                <div class="form-group">
                                                    <label>YouTube Channel URL</label>
                                                    <input type="url" class="form-control" name="youtube_url">
                                                </div>
                                                <button type="submit" class="btn btn-primary">Save Social Media Settings</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<script>
$(document).ready(function() {
    loadSettings();
});

function loadSettings() {
    $.ajax({
        url: 'api/system/fetch_system_settings.php',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                // Populate form fields with settings
                Object.keys(response.settings).forEach(function(key) {
                    const element = $(`[name="${key}"]`);
                    if (element.length) {
                        if (element.is(':checkbox')) {
                            element.prop('checked', response.settings[key] == 1);
                        } else {
                            element.val(response.settings[key]);
                        }
                    }
                });
            }
        }
    });
}

function testEmail() {
    const formData = $('#emailConfigForm').serialize();
    
    $.ajax({
        url: 'api/send_test_email.php',
        type: 'POST',
        data: formData,
        success: function(response) {
            if (response.success) {
                toastr.success('Test email sent successfully!');
            } else {
                toastr.error('Failed to send test email: ' + response.message);
            }
        }
    });
}

function createBackup() {
    $.ajax({
        url: 'api/system/create_backup.php',
        type: 'POST',
        success: function(response) {
            if (response.success) {
                toastr.success('Backup created successfully!');
                // Trigger download
                window.location.href = 'api/system/download_backup.php?file=' + response.filename;
            } else {
                toastr.error('Failed to create backup: ' + response.message);
            }
        }
    });
}

function restoreBackup() {
    const fileInput = document.getElementById('restoreFile');
    if (!fileInput.files.length) {
        toastr.error('Please select a backup file to restore');
        return;
    }

    const formData = new FormData();
    formData.append('backup_file', fileInput.files[0]);

    $.ajax({
        url: 'api/system/restore_backup.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                toastr.success('Backup restored successfully!');
            } else {
                toastr.error('Failed to restore backup: ' + response.message);
            }
        }
    });
}

// Form submissions
$('#generalSettingsForm').on('submit', function(e) {
    e.preventDefault();
    saveSettings('general', $(this).serialize());
});

$('#organizationForm').on('submit', function(e) {
    e.preventDefault();
    saveSettings('organization', $(this).serialize());
});

$('#emailConfigForm').on('submit', function(e) {
    e.preventDefault();
    saveSettings('email', $(this).serialize());
});

$('#securitySettingsForm').on('submit', function(e) {
    e.preventDefault();
    saveSettings('security', $(this).serialize());
});

$('#membershipSettingsForm').on('submit', function(e) {
    e.preventDefault();
    saveSettings('membership', $(this).serialize());
});

$('#notificationSettingsForm').on('submit', function(e) {
    e.preventDefault();
    saveSettings('notifications', $(this).serialize());
});

$('#autoBackupForm').on('submit', function(e) {
    e.preventDefault();
    saveSettings('backup', $(this).serialize());
});

$('#paymentIntegrationForm').on('submit', function(e) {
    e.preventDefault();
    saveSettings('payment', $(this).serialize());
});

$('#socialMediaForm').on('submit', function(e) {
    e.preventDefault();
    saveSettings('social', $(this).serialize());
});

function saveSettings(category, formData) {
    $.ajax({
        url: 'api/system/save_system_settings.php',
        type: 'POST',
        data: formData + '&category=' + category,
        success: function(response) {
            if (response.success) {
                toastr.success('Settings saved successfully!');
            } else {
                toastr.error('Failed to save settings: ' + response.message);
            }
        }
    });
}
</script>

<?php require_once 'templates/footer.php'; ?>
