<?php
/**
 * General System Settings
 * Configure application-wide settings
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../includes/validation.php';

requireAdmin();

$pdo = getDB();
$error = '';
$success = '';

// Load current settings from database or config file
// For this example, we'll use a settings table or config file
$settings = [];

// Check if settings table exists, if not create it
$stmt = $pdo->query("SHOW TABLES LIKE 'settings'");
if ($stmt->rowCount() == 0) {
    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        id INT PRIMARY KEY AUTO_INCREMENT,
        setting_key VARCHAR(100) UNIQUE NOT NULL,
        setting_value TEXT,
        setting_type ENUM('text', 'number', 'boolean', 'json') DEFAULT 'text',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");
    
    // Insert default settings
    $defaultSettings = [
        ['app_name', APP_NAME, 'text'],
        ['app_version', APP_VERSION, 'text'],
        ['timezone', APP_TIMEZONE, 'text'],
        ['items_per_page', ITEMS_PER_PAGE, 'number'],
        ['maintenance_mode', '0', 'boolean'],
        ['registration_enabled', '1', 'boolean'],
        ['email_notifications', '1', 'boolean'],
        ['smtp_host', '', 'text'],
        ['smtp_port', '587', 'number'],
        ['smtp_user', '', 'text'],
        ['smtp_pass', '', 'text'],
        ['date_format', 'd-m-Y', 'text'],
        ['time_format', 'H:i:s', 'text'],
        ['currency_symbol', '₹', 'text'],
        ['currency_code', 'INR', 'text']
    ];
    
    $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, setting_type) VALUES (?, ?, ?)");
    foreach ($defaultSettings as $setting) {
        $stmt->execute($setting);
    }
}

// Load all settings
$stmt = $pdo->query("SELECT setting_key, setting_value, setting_type FROM settings");
while ($row = $stmt->fetch()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $appName = trim($_POST['app_name']);
        $timezone = $_POST['timezone'];
        $itemsPerPage = (int)$_POST['items_per_page'];
        $maintenanceMode = isset($_POST['maintenance_mode']) ? 1 : 0;
        $registrationEnabled = isset($_POST['registration_enabled']) ? 1 : 0;
        $emailNotifications = isset($_POST['email_notifications']) ? 1 : 0;
        $dateFormat = $_POST['date_format'];
        $timeFormat = $_POST['time_format'];
        $currencySymbol = $_POST['currency_symbol'];
        $currencyCode = $_POST['currency_code'];
        
        // Validation
        $errors = [];
        if (empty($appName)) $errors[] = "App name is required";
        if ($itemsPerPage < 5 || $itemsPerPage > 100) $errors[] = "Items per page must be between 5 and 100";
        
        if (empty($errors)) {
            // Update settings
            $updateStmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ?");
            
            $updateStmt->execute([$appName, 'app_name']);
            $updateStmt->execute([$timezone, 'timezone']);
            $updateStmt->execute([$itemsPerPage, 'items_per_page']);
            $updateStmt->execute([$maintenanceMode, 'maintenance_mode']);
            $updateStmt->execute([$registrationEnabled, 'registration_enabled']);
            $updateStmt->execute([$emailNotifications, 'email_notifications']);
            $updateStmt->execute([$dateFormat, 'date_format']);
            $updateStmt->execute([$timeFormat, 'time_format']);
            $updateStmt->execute([$currencySymbol, 'currency_symbol']);
            $updateStmt->execute([$currencyCode, 'currency_code']);
            
            // Update constants or session
            $_SESSION['settings'] = $settings;
            $success = "Settings saved successfully!";
            
            // Refresh settings array
            $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
            $settings = [];
            while ($row = $stmt->fetch()) {
                $settings[$row['setting_key']] = $row['setting_value'];
            }
        } else {
            $error = implode("<br>", $errors);
        }
    }
}

// Get available timezones
$timezones = DateTimeZone::listIdentifiers();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>General Settings - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px 20px;
        }
        .settings-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .settings-card .card-header {
            background: #f8f9fa;
            border-bottom: 1px solid #e0e0e0;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin Panel</h4>
                    <small class="text-muted"><?php echo APP_VERSION; ?></small>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">
                        <i class="fas fa-tachometer-alt"></i> Dashboard
                    </a>
                    <a class="nav-link" href="../doctors/index.php">
                        <i class="fas fa-user-md"></i> Doctors
                    </a>
                    <a class="nav-link" href="../subscriptions/index.php">
                        <i class="fas fa-credit-card"></i> Subscriptions
                    </a>
                    <a class="nav-link" href="../rubrics/index.php">
                        <i class="fas fa-tree"></i> Rubrics
                    </a>
                    <a class="nav-link" href="../remedies/index.php">
                        <i class="fas fa-capsules"></i> Remedies
                    </a>
                    <a class="nav-link active" href="index.php">
                        <i class="fas fa-cog"></i> Settings
                    </a>
                    <a class="nav-link" href="../profile.php">
                        <i class="fas fa-user"></i> My Profile
                    </a>
                    <hr class="bg-secondary">
                    <a class="nav-link" href="../../logout.php">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </nav>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4 class="mb-0"><i class="fas fa-cog"></i> System Settings</h4>
                    </div>
                </div>
                
                <div class="p-4">
                    <?php if ($success): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <form method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <!-- General Settings -->
                                <div class="settings-card">
                                    <div class="card-header">
                                        <i class="fas fa-globe"></i> General Settings
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label for="app_name" class="form-label">Application Name</label>
                                            <input type="text" class="form-control" id="app_name" name="app_name" 
                                                   value="<?php echo escape($settings['app_name'] ?? APP_NAME); ?>" required>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="timezone" class="form-label">Default Timezone</label>
                                            <select class="form-control" id="timezone" name="timezone">
                                                <?php foreach ($timezones as $tz): ?>
                                                    <option value="<?php echo $tz; ?>" <?php echo ($settings['timezone'] ?? APP_TIMEZONE) == $tz ? 'selected' : ''; ?>>
                                                        <?php echo $tz; ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="items_per_page" class="form-label">Items Per Page</label>
                                            <input type="number" class="form-control" id="items_per_page" name="items_per_page" 
                                                   value="<?php echo $settings['items_per_page'] ?? ITEMS_PER_PAGE; ?>" min="5" max="100">
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Date & Time Format -->
                                <div class="settings-card">
                                    <div class="card-header">
                                        <i class="fas fa-calendar-alt"></i> Date & Time Format
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label for="date_format" class="form-label">Date Format</label>
                                            <select class="form-control" id="date_format" name="date_format">
                                                <option value="d-m-Y" <?php echo ($settings['date_format'] ?? 'd-m-Y') == 'd-m-Y' ? 'selected' : ''; ?>>DD-MM-YYYY (25-12-2024)</option>
                                                <option value="m-d-Y" <?php echo ($settings['date_format'] ?? 'd-m-Y') == 'm-d-Y' ? 'selected' : ''; ?>>MM-DD-YYYY (12-25-2024)</option>
                                                <option value="Y-m-d" <?php echo ($settings['date_format'] ?? 'd-m-Y') == 'Y-m-d' ? 'selected' : ''; ?>>YYYY-MM-DD (2024-12-25)</option>
                                                <option value="d/m/Y" <?php echo ($settings['date_format'] ?? 'd-m-Y') == 'd/m/Y' ? 'selected' : ''; ?>>DD/MM/YYYY (25/12/2024)</option>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="time_format" class="form-label">Time Format</label>
                                            <select class="form-control" id="time_format" name="time_format">
                                                <option value="H:i:s" <?php echo ($settings['time_format'] ?? 'H:i:s') == 'H:i:s' ? 'selected' : ''; ?>>24-hour (14:30:00)</option>
                                                <option value="h:i:s A" <?php echo ($settings['time_format'] ?? 'H:i:s') == 'h:i:s A' ? 'selected' : ''; ?>>12-hour (02:30:00 PM)</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <!-- Feature Toggles -->
                                <div class="settings-card">
                                    <div class="card-header">
                                        <i class="fas fa-toggle-on"></i> Feature Settings
                                    </div>
                                    <div class="card-body">
                                        <div class="form-check form-switch mb-3">
                                            <input class="form-check-input" type="checkbox" id="maintenance_mode" name="maintenance_mode" 
                                                   <?php echo ($settings['maintenance_mode'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="maintenance_mode">
                                                Maintenance Mode
                                            </label>
                                            <small class="text-muted d-block">When enabled, only admins can access the system</small>
                                        </div>
                                        
                                        <div class="form-check form-switch mb-3">
                                            <input class="form-check-input" type="checkbox" id="registration_enabled" name="registration_enabled" 
                                                   <?php echo ($settings['registration_enabled'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="registration_enabled">
                                                Allow Doctor Registration
                                            </label>
                                            <small class="text-muted d-block">Allow new doctors to register themselves</small>
                                        </div>
                                        
                                        <div class="form-check form-switch mb-3">
                                            <input class="form-check-input" type="checkbox" id="email_notifications" name="email_notifications" 
                                                   <?php echo ($settings['email_notifications'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="email_notifications">
                                                Email Notifications
                                            </label>
                                            <small class="text-muted d-block">Send email notifications for subscriptions, follow-ups, etc.</small>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Currency Settings -->
                                <div class="settings-card">
                                    <div class="card-header">
                                        <i class="fas fa-dollar-sign"></i> Currency Settings
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label for="currency_symbol" class="form-label">Currency Symbol</label>
                                            <input type="text" class="form-control" id="currency_symbol" name="currency_symbol" 
                                                   value="<?php echo escape($settings['currency_symbol'] ?? '₹'); ?>" maxlength="5">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="currency_code" class="form-label">Currency Code</label>
                                            <select class="form-control" id="currency_code" name="currency_code">
                                                <option value="INR" <?php echo ($settings['currency_code'] ?? 'INR') == 'INR' ? 'selected' : ''; ?>>INR - Indian Rupee</option>
                                                <option value="USD" <?php echo ($settings['currency_code'] ?? 'INR') == 'USD' ? 'selected' : ''; ?>>USD - US Dollar</option>
                                                <option value="EUR" <?php echo ($settings['currency_code'] ?? 'INR') == 'EUR' ? 'selected' : ''; ?>>EUR - Euro</option>
                                                <option value="GBP" <?php echo ($settings['currency_code'] ?? 'INR') == 'GBP' ? 'selected' : ''; ?>>GBP - British Pound</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="text-center mt-3">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-save"></i> Save All Settings
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>