<?php
session_start();
require_once 'config.php';

// Simple admin login
$admin_password = 'admin123';

// Check if logged in
if (!isset($_SESSION['admin_logged_in'])) {
    $_SESSION['admin_logged_in'] = false;
}

// Handle login
if (isset($_POST['login'])) {
    if ($_POST['password'] == $admin_password) {
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['success'] = 'Logged in successfully!';
    } else {
        $_SESSION['error'] = 'Wrong password!';
    }
    header('Location: admin_config.php');
    exit;
}

// Handle logout
if (isset($_GET['logout'])) {
    $_SESSION['admin_logged_in'] = false;
    session_destroy();
    header('Location: admin_config.php');
    exit;
}

// --- Handle Form Submissions ---
if ($_SESSION['admin_logged_in']) {
    
    // 1. Add/Update Doctor
    if (isset($_POST['save_doctor'])) {
        $id = intval($_POST['doctor_id'] ?? 0);
        $name = mysqli_real_escape_string($conn, $_POST['name']);
        $qualification = mysqli_real_escape_string($conn, $_POST['qualification'] ?? '');
        $specialty = mysqli_real_escape_string($conn, $_POST['specialty'] ?? '');
        $description = mysqli_real_escape_string($conn, $_POST['description'] ?? '');
        $status = $_POST['status'] ?? 'active';
        $display_order = intval($_POST['display_order'] ?? 0);

        $image_path = '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $target_dir = "uploads/doctors/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
            $image_name = time() . '_' . basename($_FILES['image']['name']);
            $target_file = $target_dir . $image_name;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
                $image_path = $target_file;
            }
        }

        if ($id > 0) {
            $query = "UPDATE doctors SET 
                      name='$name', 
                      qualification='$qualification', 
                      specialty='$specialty', 
                      description='$description', 
                      status='$status', 
                      display_order=$display_order";
            if ($image_path) $query .= ", image='$image_path'";
            $query .= " WHERE id=$id";
            mysqli_query($conn, $query);
            $_SESSION['success'] = "Doctor updated successfully!";
        } else {
            $query = "INSERT INTO doctors (name, qualification, specialty, description, image, status, display_order) 
                      VALUES ('$name', '$qualification', '$specialty', '$description', '$image_path', '$status', $display_order)";
            mysqli_query($conn, $query);
            $_SESSION['success'] = "Doctor added successfully!";
        }
        header('Location: admin_config.php#doctors');
        exit;
    }

    // 2. Delete Doctor
    if (isset($_GET['delete_doctor'])) {
        $id = intval($_GET['delete_doctor']);
        mysqli_query($conn, "DELETE FROM doctors WHERE id=$id");
        $_SESSION['success'] = "Doctor deleted!";
        header('Location: admin_config.php#doctors');
        exit;
    }

    // 3. Add/Update Chamber
    if (isset($_POST['save_chamber'])) {
        $id = intval($_POST['chamber_id'] ?? 0);
        $name = mysqli_real_escape_string($conn, $_POST['name']);
        $address = mysqli_real_escape_string($conn, $_POST['address']);
        $phone = mysqli_real_escape_string($conn, $_POST['phone'] ?? '');
        $status = $_POST['status'] ?? 'active';
        $display_order = intval($_POST['display_order'] ?? 0);

        $image_path = '';
        if (isset($_FILES['chamber_image']) && $_FILES['chamber_image']['error'] == 0) {
            $target_dir = "uploads/chambers/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
            $image_name = time() . '_' . basename($_FILES['chamber_image']['name']);
            $target_file = $target_dir . $image_name;
            if (move_uploaded_file($_FILES['chamber_image']['tmp_name'], $target_file)) {
                $image_path = $target_file;
            }
        }

        if ($id > 0) {
            $query = "UPDATE chambers SET 
                      name='$name', 
                      address='$address', 
                      phone='$phone', 
                      status='$status', 
                      display_order=$display_order";
            if ($image_path) $query .= ", image='$image_path'";
            $query .= " WHERE id=$id";
            mysqli_query($conn, $query);
            $_SESSION['success'] = "Chamber updated!";
        } else {
            $query = "INSERT INTO chambers (name, address, phone, image, status, display_order) 
                      VALUES ('$name', '$address', '$phone', '$image_path', '$status', $display_order)";
            mysqli_query($conn, $query);
            $_SESSION['success'] = "Chamber added!";
        }
        header('Location: admin_config.php#chambers');
        exit;
    }

    // 4. Delete Chamber
    if (isset($_GET['delete_chamber'])) {
        $id = intval($_GET['delete_chamber']);
        mysqli_query($conn, "DELETE FROM chambers WHERE id=$id");
        $_SESSION['success'] = "Chamber deleted!";
        header('Location: admin_config.php#chambers');
        exit;
    }

    // 5. Save Schedule
    if (isset($_POST['save_schedule'])) {
        $chamber_id = intval($_POST['schedule_chamber_id']);
        mysqli_query($conn, "DELETE FROM chamber_schedules WHERE chamber_id=$chamber_id");
        
        foreach ($_POST['schedule'] as $day => $data) {
            if (isset($data['active']) && $data['active'] == 1) {
                $start = mysqli_real_escape_string($conn, $data['start']);
                $end = mysqli_real_escape_string($conn, $data['end']);
                $duration = intval($data['duration'] ?? 30);
                $is_free_camp = isset($data['free_camp']) ? 1 : 0;
                $status = $data['status'] ?? 'active';
                
                $query = "INSERT INTO chamber_schedules 
                          (chamber_id, day_of_week, start_time, end_time, slot_duration, is_free_camp, status) 
                          VALUES ($chamber_id, $day, '$start', '$end', $duration, $is_free_camp, '$status')";
                mysqli_query($conn, $query);
            }
        }
        $_SESSION['success'] = "Schedule saved!";
        header('Location: admin_config.php#schedule');
        exit;
    }

    // 6. Save Settings
    if (isset($_POST['save_settings'])) {
        foreach ($_POST['settings'] as $key => $value) {
            $value = mysqli_real_escape_string($conn, $value);
            // Check if setting exists
            $check = mysqli_query($conn, "SELECT id FROM admin_settings WHERE setting_key='$key'");
            if (mysqli_num_rows($check) > 0) {
                mysqli_query($conn, "UPDATE admin_settings SET setting_value='$value' WHERE setting_key='$key'");
            } else {
                mysqli_query($conn, "INSERT INTO admin_settings (setting_key, setting_value, setting_type) VALUES ('$key', '$value', 'text')");
            }
        }
        $_SESSION['success'] = "Settings saved!";
        header('Location: admin_config.php#settings');
        exit;
    }

    // 7. Test SMS
    if (isset($_POST['test_sms'])) {
        $test_number = ADMIN_PHONE;
        $test_message = "Test SMS from Doctor Portal. Configuration is working!";
        $result = sendSMS($test_number, $test_message);
        $_SESSION['sms_test'] = $result ? "SMS sent successfully!" : "SMS failed to send. Check credentials.";
        header('Location: admin_config.php#settings');
        exit;
    }
}

// --- Fetch Data ---
$doctors = mysqli_query($conn, "SELECT * FROM doctors ORDER BY display_order, name");
$chambers = mysqli_query($conn, "SELECT * FROM chambers ORDER BY display_order, name");

// Get settings
$settings_result = mysqli_query($conn, "SELECT * FROM admin_settings");
$settings = array();
if ($settings_result) {
    while ($row = mysqli_fetch_assoc($settings_result)) {
        $settings[$row['setting_key']] = $row;
    }
}

// Get all chambers for schedule dropdown
$all_chambers = mysqli_query($conn, "SELECT * FROM chambers WHERE status='active' ORDER BY name");

// Helper function to get setting value
function getSettingValue($key, $default = '') {
    global $settings;
    if (isset($settings[$key])) {
        return $settings[$key]['setting_value'];
    }
    return $default;
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Configuration - ডা. মোঃ ফেরদৌস</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { background: #f4f6f9; font-family: 'SolaimanLipi', Arial, sans-serif; }
        .container { max-width: 1200px; margin: 20px auto; }
        .nav-tabs .nav-link { color: #2c3e50; font-weight: 600; }
        .nav-tabs .nav-link.active { background: #1a5276; color: white; }
        .tab-content { background: white; padding: 25px; border-radius: 0 0 10px 10px; border: 1px solid #dee2e6; border-top: none; }
        .card-header { background: #1a5276; color: white; }
        .doctor-card, .chamber-card { 
            border: 1px solid #e0e0e0; 
            border-radius: 10px; 
            padding: 15px;
            margin-bottom: 15px;
            background: #fafafa;
            transition: all 0.3s;
        }
        .doctor-card:hover, .chamber-card:hover { box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .doctor-image, .chamber-image {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid #1a5276;
        }
        .placeholder-image {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
            font-size: 24px;
            border: 3px solid #1a5276;
        }
        .login-box { max-width: 400px; margin: 100px auto; }
        .settings-group { margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee; }
        .settings-group:last-child { border-bottom: none; }
        .sms-status { padding: 10px; border-radius: 5px; margin-top: 10px; }
        .sms-status.success { background: #d4edda; color: #155724; }
        .sms-status.error { background: #f8d7da; color: #721c24; }
    </style>
</head>
<body>

<div class="container">
    <?php if (!$_SESSION['admin_logged_in']): ?>
        <!-- Login Form -->
        <div class="login-box card">
            <div class="card-header"><h4><i class="fas fa-lock"></i> Admin Login</h4></div>
            <div class="card-body">
                <?php if (isset($_SESSION['error'])): ?>
                    <div class="alert alert-danger"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></div>
                <?php endif; ?>
                <form method="post">
                    <div class="mb-3">
                        <label>Password</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <button type="submit" name="login" class="btn btn-primary w-100">Login</button>
                </form>
                <small class="text-muted mt-3 d-block">Default password: admin123</small>
            </div>
        </div>
    <?php else: ?>
        <!-- Admin Panel -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-cog"></i> Admin Configuration</h2>
            <div>
                <a href="?logout=1" class="btn btn-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </div>

        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['sms_test'])): ?>
            <div class="alert alert-<?php echo strpos($_SESSION['sms_test'], 'successfully') !== false ? 'success' : 'danger'; ?> alert-dismissible fade show">
                <i class="fas fa-<?php echo strpos($_SESSION['sms_test'], 'successfully') !== false ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                <?php echo $_SESSION['sms_test']; unset($_SESSION['sms_test']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Tabs -->
        <ul class="nav nav-tabs" id="configTabs" role="tablist">
            <li class="nav-item"><a class="nav-link active" id="doctors-tab" data-bs-toggle="tab" href="#doctors">👨‍⚕️ Doctors</a></li>
            <li class="nav-item"><a class="nav-link" id="chambers-tab" data-bs-toggle="tab" href="#chambers">🏥 Chambers</a></li>
            <li class="nav-item"><a class="nav-link" id="schedule-tab" data-bs-toggle="tab" href="#schedule">📅 Schedules</a></li>
            <li class="nav-item"><a class="nav-link" id="settings-tab" data-bs-toggle="tab" href="#settings">⚙️ Settings</a></li>
        </ul>

        <div class="tab-content" id="configTabsContent">
            
            <!-- ==================== DOCTORS TAB ==================== -->
            <div class="tab-pane fade show active" id="doctors">
                <div class="row">
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header"><?php echo isset($_GET['edit_doctor']) ? 'Edit' : 'Add'; ?> Doctor</div>
                            <div class="card-body">
                                <form method="post" enctype="multipart/form-data">
                                    <?php 
                                    $edit_doctor = null;
                                    if (isset($_GET['edit_doctor'])) {
                                        $id = intval($_GET['edit_doctor']);
                                        $result = mysqli_query($conn, "SELECT * FROM doctors WHERE id=$id");
                                        $edit_doctor = mysqli_fetch_assoc($result);
                                    }
                                    ?>
                                    <input type="hidden" name="doctor_id" value="<?php echo $edit_doctor['id'] ?? 0; ?>">
                                    <div class="mb-2">
                                        <label>Name *</label>
                                        <input type="text" name="name" class="form-control" required value="<?php echo htmlspecialchars($edit_doctor['name'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label>Qualification</label>
                                        <input type="text" name="qualification" class="form-control" value="<?php echo htmlspecialchars($edit_doctor['qualification'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label>Specialty</label>
                                        <input type="text" name="specialty" class="form-control" value="<?php echo htmlspecialchars($edit_doctor['specialty'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label>Description</label>
                                        <textarea name="description" class="form-control" rows="2"><?php echo htmlspecialchars($edit_doctor['description'] ?? ''); ?></textarea>
                                    </div>
                                    <div class="mb-2">
                                        <label>Image</label>
                                        <?php if (!empty($edit_doctor['image']) && file_exists($edit_doctor['image'])): ?>
                                            <div><img src="<?php echo $edit_doctor['image']; ?>" style="max-width:80px;border-radius:8px;"></div>
                                        <?php endif; ?>
                                        <input type="file" name="image" class="form-control" accept="image/*">
                                    </div>
                                    <div class="mb-2">
                                        <label>Status</label>
                                        <select name="status" class="form-select">
                                            <option value="active" <?php echo ($edit_doctor['status'] ?? '') == 'active' ? 'selected' : ''; ?>>Active</option>
                                            <option value="inactive" <?php echo ($edit_doctor['status'] ?? '') == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                        </select>
                                    </div>
                                    <div class="mb-2">
                                        <label>Display Order</label>
                                        <input type="number" name="display_order" class="form-control" value="<?php echo $edit_doctor['display_order'] ?? 0; ?>">
                                    </div>
                                    <button type="submit" name="save_doctor" class="btn btn-primary w-100">
                                        <i class="fas fa-save"></i> <?php echo isset($_GET['edit_doctor']) ? 'Update' : 'Add'; ?>
                                    </button>
                                    <?php if (isset($_GET['edit_doctor'])): ?>
                                        <a href="admin_config.php#doctors" class="btn btn-secondary w-100 mt-2">Cancel</a>
                                    <?php endif; ?>
                                </form>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header">Doctor List</div>
                            <div class="card-body">
                                <?php if ($doctors && mysqli_num_rows($doctors) > 0): ?>
                                    <?php while ($doctor = mysqli_fetch_assoc($doctors)): ?>
                                        <div class="doctor-card d-flex align-items-center">
                                            <div>
                                                <?php if (!empty($doctor['image']) && file_exists($doctor['image'])): ?>
                                                    <img src="<?php echo $doctor['image']; ?>" class="doctor-image">
                                                <?php else: ?>
                                                    <div class="placeholder-image"><i class="fas fa-user-md"></i></div>
                                                <?php endif; ?>
                                            </div>
                                            <div class="flex-grow-1 ms-3">
                                                <h5><?php echo htmlspecialchars($doctor['name']); ?></h5>
                                                <small><?php echo htmlspecialchars($doctor['qualification'] ?? 'N/A'); ?> - <?php echo htmlspecialchars($doctor['specialty'] ?? 'N/A'); ?></small>
                                                <span class="badge bg-<?php echo ($doctor['status'] ?? 'inactive') == 'active' ? 'success' : 'secondary'; ?>">
                                                    <?php echo $doctor['status'] ?? 'inactive'; ?>
                                                </span>
                                                <span class="badge bg-info">Order: <?php echo $doctor['display_order'] ?? 0; ?></span>
                                            </div>
                                            <div>
                                                <a href="?edit_doctor=<?php echo $doctor['id']; ?>" class="btn btn-sm btn-primary"><i class="fas fa-edit"></i></a>
                                                <a href="?delete_doctor=<?php echo $doctor['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this doctor?')"><i class="fas fa-trash"></i></a>
                                            </div>
                                        </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <div class="alert alert-info">No doctors found. Add your first doctor!</div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ==================== CHAMBERS TAB ==================== -->
            <div class="tab-pane fade" id="chambers">
                <div class="row">
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header"><?php echo isset($_GET['edit_chamber']) ? 'Edit' : 'Add'; ?> Chamber</div>
                            <div class="card-body">
                                <form method="post" enctype="multipart/form-data">
                                    <?php 
                                    $edit_chamber = null;
                                    if (isset($_GET['edit_chamber'])) {
                                        $id = intval($_GET['edit_chamber']);
                                        $result = mysqli_query($conn, "SELECT * FROM chambers WHERE id=$id");
                                        $edit_chamber = mysqli_fetch_assoc($result);
                                    }
                                    ?>
                                    <input type="hidden" name="chamber_id" value="<?php echo $edit_chamber['id'] ?? 0; ?>">
                                    <div class="mb-2">
                                        <label>Chamber Name *</label>
                                        <input type="text" name="name" class="form-control" required value="<?php echo htmlspecialchars($edit_chamber['name'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label>Address *</label>
                                        <textarea name="address" class="form-control" required rows="2"><?php echo htmlspecialchars($edit_chamber['address'] ?? ''); ?></textarea>
                                    </div>
                                    <div class="mb-2">
                                        <label>Phone</label>
                                        <input type="text" name="phone" class="form-control" value="<?php echo htmlspecialchars($edit_chamber['phone'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label>Image</label>
                                        <?php if (!empty($edit_chamber['image']) && file_exists($edit_chamber['image'])): ?>
                                            <div><img src="<?php echo $edit_chamber['image']; ?>" style="max-width:80px;border-radius:8px;"></div>
                                        <?php endif; ?>
                                        <input type="file" name="chamber_image" class="form-control" accept="image/*">
                                    </div>
                                    <div class="mb-2">
                                        <label>Status</label>
                                        <select name="status" class="form-select">
                                            <option value="active" <?php echo ($edit_chamber['status'] ?? '') == 'active' ? 'selected' : ''; ?>>Active</option>
                                            <option value="inactive" <?php echo ($edit_chamber['status'] ?? '') == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                        </select>
                                    </div>
                                    <div class="mb-2">
                                        <label>Display Order</label>
                                        <input type="number" name="display_order" class="form-control" value="<?php echo $edit_chamber['display_order'] ?? 0; ?>">
                                    </div>
                                    <button type="submit" name="save_chamber" class="btn btn-primary w-100">
                                        <i class="fas fa-save"></i> <?php echo isset($_GET['edit_chamber']) ? 'Update' : 'Add'; ?> Chamber
                                    </button>
                                    <?php if (isset($_GET['edit_chamber'])): ?>
                                        <a href="admin_config.php#chambers" class="btn btn-secondary w-100 mt-2">Cancel</a>
                                    <?php endif; ?>
                                </form>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header">Chamber List</div>
                            <div class="card-body">
                                <?php if ($chambers && mysqli_num_rows($chambers) > 0): ?>
                                    <?php while ($chamber = mysqli_fetch_assoc($chambers)): ?>
                                        <div class="chamber-card d-flex align-items-center">
                                            <div>
                                                <?php if (!empty($chamber['image']) && file_exists($chamber['image'])): ?>
                                                    <img src="<?php echo $chamber['image']; ?>" class="chamber-image">
                                                <?php else: ?>
                                                    <div class="placeholder-image"><i class="fas fa-hospital"></i></div>
                                                <?php endif; ?>
                                            </div>
                                            <div class="flex-grow-1 ms-3">
                                                <h5><?php echo htmlspecialchars($chamber['name']); ?></h5>
                                                <small><?php echo htmlspecialchars($chamber['address'] ?? 'N/A'); ?></small>
                                                <span class="badge bg-<?php echo ($chamber['status'] ?? 'inactive') == 'active' ? 'success' : 'secondary'; ?>">
                                                    <?php echo $chamber['status'] ?? 'inactive'; ?>
                                                </span>
                                                <span class="badge bg-info">Order: <?php echo $chamber['display_order'] ?? 0; ?></span>
                                            </div>
                                            <div>
                                                <a href="?edit_chamber=<?php echo $chamber['id']; ?>" class="btn btn-sm btn-primary"><i class="fas fa-edit"></i></a>
                                                <a href="?delete_chamber=<?php echo $chamber['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this chamber?')"><i class="fas fa-trash"></i></a>
                                            </div>
                                        </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <div class="alert alert-info">No chambers found. Add your first chamber!</div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ==================== SCHEDULE TAB ==================== -->
            <div class="tab-pane fade" id="schedule">
                <div class="card">
                    <div class="card-header">Chamber Schedules</div>
                    <div class="card-body">
                        <form method="post">
                            <div class="mb-3">
                                <label>Select Chamber</label>
                                <select name="schedule_chamber_id" id="schedule_chamber_id" class="form-select">
                                    <option value="">-- Select --</option>
                                    <?php if ($all_chambers): ?>
                                        <?php while ($ch = mysqli_fetch_assoc($all_chambers)): ?>
                                            <option value="<?php echo $ch['id']; ?>" <?php echo (isset($_GET['schedule_chamber']) && $_GET['schedule_chamber'] == $ch['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($ch['name']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    <?php endif; ?>
                                </select>
                            </div>

                            <div id="schedule_form" style="<?php echo isset($_GET['schedule_chamber']) ? 'display:block' : 'display:none'; ?>">
                                <?php 
                                $existing_schedule = array();
                                if (isset($_GET['schedule_chamber'])) {
                                    $ch_id = intval($_GET['schedule_chamber']);
                                    $sch_query = mysqli_query($conn, "SELECT * FROM chamber_schedules WHERE chamber_id=$ch_id");
                                    if ($sch_query) {
                                        while ($sch = mysqli_fetch_assoc($sch_query)) {
                                            $existing_schedule[$sch['day_of_week']] = $sch;
                                        }
                                    }
                                }
                                ?>
                                <table class="table table-bordered">
                                    <thead>
                                        <tr><th>Day</th><th>Active</th><th>Start</th><th>End</th><th>Slot (min)</th><th>Free Camp</th><th>Status</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
                                        foreach ($days as $index => $day_name): 
                                            $existing = isset($existing_schedule[$index]) ? $existing_schedule[$index] : null;
                                        ?>
                                        <tr>
                                            <td><strong><?php echo $day_name; ?></strong></td>
                                            <td><input type="checkbox" name="schedule[<?php echo $index; ?>][active]" <?php echo $existing ? 'checked' : ''; ?>></td>
                                            <td><input type="time" name="schedule[<?php echo $index; ?>][start]" value="<?php echo $existing['start_time'] ?? '09:00'; ?>" <?php echo $existing ? '' : 'disabled'; ?>></td>
                                            <td><input type="time" name="schedule[<?php echo $index; ?>][end]" value="<?php echo $existing['end_time'] ?? '17:00'; ?>" <?php echo $existing ? '' : 'disabled'; ?>></td>
                                            <td><input type="number" name="schedule[<?php echo $index; ?>][duration]" value="<?php echo $existing['slot_duration'] ?? 30; ?>" <?php echo $existing ? '' : 'disabled'; ?> min="15" step="5"></td>
                                            <td><input type="checkbox" name="schedule[<?php echo $index; ?>][free_camp]" <?php echo ($existing && $existing['is_free_camp'] == 1) ? 'checked' : ''; ?> <?php echo $existing ? '' : 'disabled'; ?>></td>
                                            <td>
                                                <select name="schedule[<?php echo $index; ?>][status]" <?php echo $existing ? '' : 'disabled'; ?>>
                                                    <option value="active" <?php echo ($existing && $existing['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                                                    <option value="inactive" <?php echo ($existing && $existing['status'] == 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                                                </select>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <button type="submit" name="save_schedule" class="btn btn-primary"><i class="fas fa-save"></i> Save Schedule</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- ==================== SETTINGS TAB ==================== -->
            <div class="tab-pane fade" id="settings">
                <form method="post">
                    <!-- General Settings -->
                    <div class="card mb-4">
                        <div class="card-header">General Settings</div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="settings-group">
                                        <label class="fw-bold">Minimum Booking Days</label>
                                        <small class="d-block text-muted">Days in advance required for booking</small>
                                        <input type="number" name="settings[min_booking_days]" class="form-control" 
                                               value="<?php echo htmlspecialchars(getSettingValue('min_booking_days', '3')); ?>">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="settings-group">
                                        <label class="fw-bold">Maximum Booking Days</label>
                                        <small class="d-block text-muted">Maximum days in advance allowed</small>
                                        <input type="number" name="settings[max_booking_days]" class="form-control" 
                                               value="<?php echo htmlspecialchars(getSettingValue('max_booking_days', '30')); ?>">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="settings-group">
                                        <label class="fw-bold">Default Slot Duration</label>
                                        <small class="d-block text-muted">Minutes per slot</small>
                                        <input type="number" name="settings[slot_duration]" class="form-control" 
                                               value="<?php echo htmlspecialchars(getSettingValue('slot_duration', '30')); ?>">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="settings-group">
                                        <label class="fw-bold">Booking Fees (JSON)</label>
                                        <small class="d-block text-muted">Format: {"regular":200,"special":500,"free_medicine":100}</small>
                                        <textarea name="settings[booking_fees]" class="form-control" rows="2"><?php echo htmlspecialchars(getSettingValue('booking_fees', '{"regular":200,"special":500,"free_medicine":100}')); ?></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- SMS Configuration -->
                    <div class="card mb-4">
                        <div class="card-header bg-info text-white">
                            <i class="fas fa-sms"></i> SMS Configuration (bulksmsbd.net)
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="settings-group">
                                        <label class="fw-bold">Enable SMS</label>
                                        <select name="settings[enable_sms]" class="form-select">
                                            <option value="true" <?php echo getSettingValue('enable_sms') == 'true' ? 'selected' : ''; ?>>Yes</option>
                                            <option value="false" <?php echo getSettingValue('enable_sms') == 'false' ? 'selected' : ''; ?>>No</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="settings-group">
                                        <label class="fw-bold">Admin Phone Number</label>
                                        <input type="text" name="settings[admin_phone]" class="form-control" 
                                               value="<?php echo htmlspecialchars(getSettingValue('admin_phone', '01775121112')); ?>">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="settings-group">
                                        <label class="fw-bold">SMS API Key</label>
                                        <input type="text" name="settings[sms_api_key]" class="form-control" 
                                               value="<?php echo htmlspecialchars(getSettingValue('sms_api_key', '')); ?>">
                                        <small class="text-muted">Get from bulksmsbd.net dashboard</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="settings-group">
                                        <label class="fw-bold">Sender ID</label>
                                        <input type="text" name="settings[sms_sender_id]" class="form-control" 
                                               value="<?php echo htmlspecialchars(getSettingValue('sms_sender_id', '8809617610000')); ?>">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="settings-group">
                                        <label class="fw-bold">Username (Optional)</label>
                                        <input type="text" name="settings[sms_username]" class="form-control" 
                                               value="<?php echo htmlspecialchars(getSettingValue('sms_username', '')); ?>">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="settings-group">
                                        <label class="fw-bold">Password (Optional)</label>
                                        <input type="text" name="settings[sms_password]" class="form-control" 
                                               value="<?php echo htmlspecialchars(getSettingValue('sms_password', '')); ?>">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-12">
                                    <div class="settings-group">
                                        <label class="fw-bold">API URL</label>
                                        <input type="text" name="settings[sms_api_url]" class="form-control" 
                                               value="<?php echo htmlspecialchars(getSettingValue('sms_api_url', 'https://bulksmsbd.net/api/smsapi')); ?>">
                                    </div>
                                </div>
                            </div>
                            <div class="alert alert-info mt-3">
                                <i class="fas fa-info-circle"></i> 
                                <strong>How to get credentials:</strong> 
                                Login to <a href="https://bulksmsbd.net" target="_blank">bulksmsbd.net</a> → Dashboard → API Settings
                            </div>
                            
                            <!-- Test SMS Button -->
                            <div class="mt-3">
                                <button type="submit" name="test_sms" class="btn btn-success">
                                    <i class="fas fa-paper-plane"></i> Send Test SMS to Admin
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Save Button -->
                    <button type="submit" name="save_settings" class="btn btn-primary btn-lg">
                        <i class="fas fa-save"></i> Save All Settings
                    </button>
                </form>
            </div>
        </div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Auto-load schedule when chamber is selected
document.getElementById('schedule_chamber_id')?.addEventListener('change', function() {
    if (this.value) {
        window.location.href = 'admin_config.php?schedule_chamber=' + this.value + '#schedule';
    }
});

// Enable/disable schedule inputs
document.querySelectorAll('.day_active')?.forEach(function(cb) {
    cb.addEventListener('change', function() {
        var row = this.closest('tr');
        var inputs = row.querySelectorAll('input:not(.day_active), select');
        inputs.forEach(function(inp) {
            inp.disabled = !this.checked;
        });
    });
});

// Preserve tab after form submission
document.addEventListener('DOMContentLoaded', function() {
    var hash = window.location.hash;
    if (hash) {
        var tab = document.querySelector('[href="' + hash + '"]');
        if (tab) {
            var tabInstance = new bootstrap.Tab(tab);
            tabInstance.show();
        }
    }
});
</script>
</body>
</html>