<?php
/**
 * Admin General Settings
 * Path: /admin/settings/index.php
 */

require_once __DIR__ . '/../../config/config.php';
requireAdmin();

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

// ============================================
// Ensure settings table exists with default values
// ============================================
$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 if missing
$defaultSettings = [
    ['app_name', 'Homoeopathy System', 'text'],
    ['app_version', '1.0.0', 'text'],
    ['timezone', 'Asia/Dhaka', 'text'],
    ['items_per_page', '20', 'number'],
    ['maintenance_mode', '0', 'boolean'],
    ['registration_enabled', '1', 'boolean'],
    ['email_notifications', '1', 'boolean'],
    ['date_format', 'd-m-Y', 'text'],
    ['time_format', 'H:i:s', 'text'],
    ['currency_symbol', '৳', 'text'],
    ['currency_code', 'BDT', 'text']
];

$checkStmt = $pdo->prepare("SELECT id FROM settings WHERE setting_key = ?");
$insertStmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, setting_type) VALUES (?, ?, ?)");
foreach ($defaultSettings as $setting) {
    $checkStmt->execute([$setting[0]]);
    if (!$checkStmt->fetch()) {
        $insertStmt->execute($setting);
    }
}

// Load current settings into array
$settings = [];
$result = $pdo->query("SELECT setting_key, setting_value FROM settings");
while ($row = $result->fetch()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// ============================================
// Process form submission
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !verifyCsrfToken($_POST['csrf_token'])) {
        $error = "Security validation failed. Please reload the page and try again.";
    } else {
        $appName = trim($_POST['app_name'] ?? '');
        $timezone = $_POST['timezone'] ?? '';
        $itemsPerPage = (int)($_POST['items_per_page'] ?? 20);
        $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'] ?? 'd-m-Y';
        $timeFormat = $_POST['time_format'] ?? 'H:i:s';
        $currencySymbol = trim($_POST['currency_symbol'] ?? '৳');
        $currencyCode = trim($_POST['currency_code'] ?? 'BDT');

        $errors = [];
        if (empty($appName)) $errors[] = "Application name cannot be empty.";
        if ($itemsPerPage < 5 || $itemsPerPage > 200) $errors[] = "Items per page must be between 5 and 200.";

        if (empty($errors)) {
            $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']);

            $message = "Settings saved successfully!";

            // Update local array
            $settings['app_name'] = $appName;
            $settings['timezone'] = $timezone;
            $settings['items_per_page'] = $itemsPerPage;
            $settings['maintenance_mode'] = $maintenanceMode;
            $settings['registration_enabled'] = $registrationEnabled;
            $settings['email_notifications'] = $emailNotifications;
            $settings['date_format'] = $dateFormat;
            $settings['time_format'] = $timeFormat;
            $settings['currency_symbol'] = $currencySymbol;
            $settings['currency_code'] = $currencyCode;
        } else {
            $error = implode("<br>", $errors);
        }
    }
}

// List of supported 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="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #1a472a 0%, #0d2818 100%);
            position: fixed;
            left: 0;
            top: 0;
            width: 260px;
            color: white;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: rgba(255,255,255,0.1);
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #2ecc71;
        }
        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
        }
        .main-content {
            margin-left: 260px;
            padding: 20px;
        }
        .top-navbar {
            background: white;
            border-radius: 12px;
            padding: 15px 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .settings-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        @media (max-width: 768px) {
            .sidebar { width: 70px; }
            .sidebar .nav-link span { display: none; }
            .main-content { margin-left: 70px; }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="text-center py-4">
            <h4 class="text-white">🏥 Admin</h4>
        </div>
        <nav class="nav flex-column">
            <a class="nav-link" href="../dashboard.php"><i class="fas fa-tachometer-alt"></i> <span>Dashboard</span></a>
            <a class="nav-link" href="../doctors/index.php"><i class="fas fa-user-md"></i> <span>Doctors</span></a>
            <a class="nav-link" href="../subscriptions/index.php"><i class="fas fa-credit-card"></i> <span>Subscriptions</span></a>
            <a class="nav-link" href="../rubrics/index.php"><i class="fas fa-tree"></i> <span>Rubrics</span></a>
            <a class="nav-link" href="../remedies/index.php"><i class="fas fa-capsules"></i> <span>Remedies</span></a>
            <a class="nav-link" href="../reports/index.php"><i class="fas fa-chart-line"></i> <span>Reports</span></a>
            <a class="nav-link active" href="index.php"><i class="fas fa-cog"></i> <span>Settings</span></a>
            <a class="nav-link" href="../profile.php"><i class="fas fa-user"></i> <span>Profile</span></a>
            <hr class="bg-secondary">
            <a class="nav-link" href="../../logout.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
        </nav>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <div class="top-navbar">
            <h4 class="mb-0"><i class="fas fa-cog"></i> General Settings</h4>
        </div>

        <div class="settings-card">
            <?php if ($message): ?>
                <div class="alert alert-success alert-dismissible fade show"><?php echo htmlspecialchars($message); ?><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"><?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 mb-3">
                        <label class="form-label">Application Name</label>
                        <input type="text" name="app_name" class="form-control" value="<?php echo htmlspecialchars($settings['app_name'] ?? 'Homoeopathy System'); ?>" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Timezone</label>
                        <select name="timezone" class="form-control">
                            <?php foreach ($timezones as $tz): ?>
                                <option value="<?php echo $tz; ?>" <?php echo ($settings['timezone'] ?? 'Asia/Dhaka') == $tz ? 'selected' : ''; ?>><?php echo $tz; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Items Per Page</label>
                        <input type="number" name="items_per_page" class="form-control" value="<?php echo $settings['items_per_page'] ?? 20; ?>" min="5" max="200">
                    </div>
                </div>

                <h5 class="mt-3">Date & Time Format</h5>
                <hr>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Date Format</label>
                        <select name="date_format" class="form-control">
                            <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>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Time Format</label>
                        <select name="time_format" class="form-control">
                            <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>

                <h5 class="mt-3">Currency</h5>
                <hr>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Currency Symbol</label>
                        <input type="text" name="currency_symbol" class="form-control" value="<?php echo htmlspecialchars($settings['currency_symbol'] ?? '৳'); ?>" maxlength="5">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Currency Code</label>
                        <select name="currency_code" class="form-control">
                            <option value="BDT" <?php echo ($settings['currency_code'] ?? 'BDT') == 'BDT' ? 'selected' : ''; ?>>BDT - Bangladeshi Taka</option>
                            <option value="USD" <?php echo ($settings['currency_code'] ?? 'BDT') == 'USD' ? 'selected' : ''; ?>>USD - US Dollar</option>
                            <option value="INR" <?php echo ($settings['currency_code'] ?? 'BDT') == 'INR' ? 'selected' : ''; ?>>INR - Indian Rupee</option>
                        </select>
                    </div>
                </div>

                <h5 class="mt-3">Feature Toggles</h5>
                <hr>
                <div class="form-check form-switch mb-2">
                    <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 (only admins can access the system)</label>
                </div>
                <div class="form-check form-switch mb-2">
                    <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>
                </div>
                <div class="form-check form-switch mb-2">
                    <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">Enable Email Notifications</label>
                </div>

                <div class="mt-4">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Settings</button>
                    <a href="../dashboard.php" class="btn btn-secondary">Cancel</a>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>