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

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$page_title = 'Slot Management';
$current_page = 'slot_management.php';
$pdo = getDBConnection();

// Get Settings for Slot Generation
function getSetting($pdo, $key, $default = '') {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->execute([$key]);
    $result = $stmt->fetchColumn();
    return $result !== false ? $result : $default;
}

$success_message = '';
$error_message = '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $date = $_POST['date'];
        $slot = $_POST['slot'] ?? '';

        try {
            if ($_POST['action'] === 'block_slot') {
                // Admin booking/blocking
                $stmt = $pdo->prepare("SELECT id FROM appointments WHERE appointment_date = ? AND time_slot = ? AND status IN ('pending', 'confirmed', 'completed')");
                $stmt->execute([$date, $slot]);
                if (!$stmt->fetch()) {
                    $stmt = $pdo->prepare("INSERT INTO appointments (user_id, user_name, user_mobile, appointment_date, time_slot, status, payment_status, amount, consultation_type) VALUES (0, 'Admin', '0000000000', ?, ?, 'confirmed', 'paid', 0, 'office_meeting')");
                    $stmt->execute([$date, $slot]);
                    $success_message = "Slot $slot confirmed for Admin successfully!";
                } else {
                    $error_message = "Slot $slot is already booked or blocked.";
                }
            } elseif ($_POST['action'] === 'unblock_slot') {
                $stmt = $pdo->prepare("DELETE FROM appointments WHERE appointment_date = ? AND time_slot = ? AND user_name = 'Admin'");
                $stmt->execute([$date, $slot]);
                $success_message = "Admin slot $slot removed successfully!";
            } elseif ($_POST['action'] === 'confirm_pending') {
                // Update a pending appointment to confirmed and paid
                $stmt = $pdo->prepare("UPDATE appointments SET status = 'confirmed', payment_status = 'paid' WHERE appointment_date = ? AND time_slot = ? AND status = 'pending' LIMIT 1");
                $stmt->execute([$date, $slot]);
                $success_message = "Pending appointment for $slot confirmed and marked as PAID!";
            } elseif ($_POST['action'] === 'toggle_day_off') {
                $stmt = $pdo->prepare("SELECT id FROM blocked_dates WHERE block_date = ?");
                $stmt->execute([$date]);
                if ($stmt->fetch()) {
                    // Day is currently OFF, turning it ON (Opening the day)
                    $stmt = $pdo->prepare("DELETE FROM blocked_dates WHERE block_date = ?");
                    $stmt->execute([$date]);
                    
                    // Delete all Admin blocks for this date
                    $stmt = $pdo->prepare("DELETE FROM appointments WHERE appointment_date = ? AND user_name = 'Admin'");
                    $stmt->execute([$date]);
                    
                    $success_message = "Day opened and all Admin blocks removed for $date";
                } else {
                    // Day is currently ON, turning it OFF (Blocking the day)
                    $stmt = $pdo->prepare("INSERT INTO blocked_dates (block_date) VALUES (?)");
                    $stmt->execute([$date]);
                    
                    // Mark all slots as block by admin
                    $s_time = getSetting($pdo, 'start_time', '09:00');
                    $e_time = getSetting($pdo, 'end_time', '18:00');
                    $s_dur = (int)getSetting($pdo, 'slot_duration', '60');
                    $s_per_h = (int)getSetting($pdo, 'slots_per_hour', '1');
                    if ($s_per_h == 3) $s_per_h = 4;
                    $act_dur = ($s_per_h > 0) ? (60 / $s_per_h) : $s_dur;

                    $c_dt = new DateTime($date . ' ' . $s_time);
                    $e_dt = new DateTime($date . ' ' . $e_time);

                    while ($c_dt < $e_dt) {
                        $s_24h = $c_dt->format('H:i');
                        $temp_dt = clone $c_dt;
                        $temp_dt->add(new DateInterval("PT" . (int)$act_dur . "M"));
                        $e_24h = $temp_dt->format('H:i');
                        $f_range = "$s_24h - $e_24h";

                        // Check if already exist to avoid duplicates or overwriting bookings
                        $checkStmt = $pdo->prepare("SELECT id FROM appointments WHERE appointment_date = ? AND time_slot = ? AND status IN ('pending', 'confirmed', 'completed')");
                        $checkStmt->execute([$date, $f_range]);
                        if (!$checkStmt->fetch()) {
                            $insertStmt = $pdo->prepare("INSERT INTO appointments (user_id, user_name, user_mobile, appointment_date, time_slot, status, payment_status, amount, consultation_type) VALUES (0, 'Admin', '0000000000', ?, ?, 'confirmed', 'paid', 0, 'office_meeting')");
                            $insertStmt->execute([$date, $f_range]);
                        }
                        $c_dt->add(new DateInterval("PT" . (int)$act_dur . "M"));
                    }
                    
                    $success_message = "Day marked as off and all slots blocked by admin for $date";
                }
            }
        } catch (Exception $e) {
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Get Selected Date
$selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// Get Settings for Slot Generation

$start_time = getSetting($pdo, 'start_time', '09:00');
$end_time = getSetting($pdo, 'end_time', '18:00');
$slot_duration_setting = (int)getSetting($pdo, 'slot_duration', '60');
$slots_per_hour = (int)getSetting($pdo, 'slots_per_hour', '1');

// Force fix as in api/get_slots.php
if ($slots_per_hour == 3) {
    $slots_per_hour = 4;
}

$actual_slot_duration = ($slots_per_hour > 0) ? (60 / $slots_per_hour) : $slot_duration_setting;

$lunch_enabled = getSetting($pdo, 'lunch_break_enabled', '0');
$lunch_start = getSetting($pdo, 'lunch_start', '13:00');
$lunch_end = getSetting($pdo, 'lunch_end', '14:00');

// Check if day is off
$stmt = $pdo->prepare("SELECT id FROM blocked_dates WHERE block_date = ?");
$stmt->execute([$selected_date]);
$is_day_off = $stmt->fetch() ? true : false;

// Get bookings for the day
$stmt = $pdo->prepare("SELECT time_slot, user_name, user_mobile, status, created_at FROM appointments WHERE appointment_date = ? AND status IN ('pending', 'pending_payment', 'confirmed', 'completed')");
$stmt->execute([$selected_date]);
$bookings_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);
$bookings = [];
$total_booked_count = 0;
$total_blocked_count = 0;

foreach ($bookings_raw as $row) {
    if ($row['user_name'] === 'Admin') {
        $total_blocked_count++;
    } elseif ($row['status'] === 'confirmed' || $row['status'] === 'completed') {
        $total_booked_count++;
    }

    // Extraction
    $normalized_time = '';
    if (preg_match('/^(\d{1,2}:\d{2}\s*(?:AM|PM|am|pm))/i', $row['time_slot'], $matches)) {
        $normalized_time = date('h:i A', strtotime($matches[1]));
    } elseif (preg_match('/^(\d{1,2}:\d{2})/', $row['time_slot'], $matches)) {
        $normalized_time = date('h:i A', strtotime($matches[1]));
    } else {
        $normalized_time = date('h:i A', strtotime($row['time_slot']));
    }

    if ($normalized_time) {
        if (!isset($bookings[$normalized_time])) {
            $bookings[$normalized_time] = [];
        }
        $bookings[$normalized_time][] = $row;
    }
}

// Generate Slots
$slots = [];
$current_dt = new DateTime($selected_date . ' ' . $start_time);
$end_dt = new DateTime($selected_date . ' ' . $end_time);

while ($current_dt < $end_dt) {
    $slot_start_display = $current_dt->format('h:i A');
    $slot_start_24h = $current_dt->format('H:i');
    
    $current_dt->add(new DateInterval("PT" . (int)$actual_slot_duration . "M"));
    $slot_end_display = $current_dt->format('h:i A');
    $slot_end_24h = $current_dt->format('H:i');
    
    $full_range = "$slot_start_24h - $slot_end_24h";
    
    $is_lunch = false;
    if ($slot_start_24h >= $lunch_start && $slot_end_24h <= $lunch_end) {
        $is_lunch = true;
    }
    
    $slots[] = [
        'time' => $slot_start_display,
        'full_range' => $full_range,
        'is_lunch' => $is_lunch
    ];
}

ob_start();
?>

<style>
    .slot-card {
        background: white;
        border-radius: 12px;
        padding: 15px;
        margin-bottom: 15px;
        box-shadow: 0 4px 10px rgba(0,0,0,0.05);
        border-left: 5px solid #e0e0e0;
        transition: all 0.3s ease;
    }
    .slot-card.booked { border-left-color: #dc3545; background: #fff8f8; }
    .slot-card.pending { border-left-color: #ffc107; background: #fffdf5; }
    .slot-card.blocked { border-left-color: #6c757d; background: #f8f9fa; }
    .slot-card.lunch { border-left-color: #ffc107; opacity: 0.7; border-style: dashed; }
    .slot-card.free { border-left-color: #007bff; }
    
    .status-badge {
        font-size: 0.75rem;
        padding: 4px 8px;
        border-radius: 10px;
        font-weight: bold;
    }
    .bg-free { background: #e7f3ff; color: #007bff; }
    .bg-booked { background: #fdeaea; color: #dc3545; }
    .bg-pending { background: #fff3cd; color: #856404; }
    .bg-blocked { background: #e9ecef; color: #6c757d; }
    .bg-lunch { background: #f8f9fa; color: #adb5bd; }
    
    .date-input {
        max-width: 250px;
        border-radius: 20px;
        padding: 10px 20px;
    }
    
    .day-off-card {
        background: #343a40;
        color: white;
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 25px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .btn-block { border-radius: 20px; font-size: 0.8rem; }
    
    .summary-item {
        text-align: center;
        padding: 10px;
        border-radius: 10px;
        background: #f8f9fa;
        flex: 1;
        margin: 0 5px;
    }
</style>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0"><i class="fas fa-calendar-alt me-2"></i>Slot Management</h2>
        <form method="GET" class="d-flex gap-2">
            <input type="date" name="date" class="form-control date-input" value="<?php echo $selected_date; ?>" onchange="this.form.submit()">
        </form>
    </div>

    <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i><?php echo $success_message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle me-2"></i><?php echo $error_message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="day-off-card">
        <div>
            <h4 class="mb-0"><?php echo date('l, d M Y', strtotime($selected_date)); ?></h4>
            <small><?php echo $is_day_off ? '🔴 Day is Blocked (Bookings Closed)' : '🟢 Day is Open (Bookings Working)'; ?></small>
        </div>
        <form method="POST">
            <input type="hidden" name="date" value="<?php echo $selected_date; ?>">
            <input type="hidden" name="action" value="toggle_day_off">
            <button type="submit" class="btn <?php echo $is_day_off ? 'btn-success' : 'btn-danger'; ?> rounded-pill">
                <?php echo $is_day_off ? 'Open for Bookings (Unblock Day)' : 'Mark as Day Off (Block Day)'; ?>
            </button>
        </form>
    </div>
    <!-- Summary -->
    <div class="d-flex mb-4">
        <div class="summary-item">
            <h6 class="text-muted">Total (Working)</h6>
            <h5><?php 
                $lunch_count = 0;
                foreach($slots as $s) if($s['is_lunch']) $lunch_count++;
                echo count($slots) - $lunch_count; 
            ?></h5>
        </div>
        <div class="summary-item">
            <h6 class="text-muted">Booked Today</h6>
            <h5 class="text-success"><?php echo $total_booked_count; ?></h5>
        </div>
        <div class="summary-item">
            <h6 class="text-muted">Blocked</h6>
            <h5 class="text-danger"><?php echo $total_blocked_count; ?></h5>
        </div>
        <div class="summary-item">
            <h6 class="text-muted">Lunch Slots</h6>
            <h5 class="text-warning"><?php echo $lunch_count; ?></h5>
        </div>
    </div>

    <?php if ($is_day_off): ?>
        <div class="text-center py-5 bg-white rounded-3 shadow-sm">
            <i class="fas fa-calendar-times fa-4x text-muted mb-3"></i>
            <h3>This day is currently blocked</h3>
            <p class="text-muted">Click the button above to unblock this day.</p>
        </div>
    <?php else: ?>
        <div class="row">
            <?php foreach ($slots as $slot): ?>
                <?php 
                    $time = $slot['time'];
                    $is_lunch = $slot['is_lunch'];
                    $slot_bookings = isset($bookings[$time]) ? $bookings[$time] : [];
                    $booking = !empty($slot_bookings) ? $slot_bookings[0] : null;
                    
                    $card_class = 'free';
                    $status_text = 'FREE';
                    $badge_class = 'bg-free';
                    
                    if ($is_lunch) {
                        $card_class = 'lunch';
                        $status_text = 'LUNCH BREAK';
                        $badge_class = 'bg-lunch';
                    } elseif ($booking) {
                        if ($booking['user_name'] === 'Admin') {
                            $card_class = 'blocked';
                            $status_text = 'ADMIN BLOCK';
                            $badge_class = 'bg-blocked';
                        } elseif ($booking['status'] === 'confirmed' || $booking['status'] === 'completed') {
                            $card_class = 'booked';
                            $status_text = 'BOOKED';
                            $badge_class = 'bg-booked';
                        } else {
                            $card_class = 'pending';
                            $status_text = 'PENDING/UNPAID';
                            $badge_class = 'bg-pending';
                        }
                    }
                ?>
                <div class="col-md-6 col-lg-4">
                    <div class="slot-card <?php echo $card_class; ?>">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <h5 class="mb-1"><?php echo $time; ?></h5>
                                <span class="status-badge <?php echo $badge_class; ?>"><?php echo $status_text; ?></span>
                            </div>
                            <?php if (!$is_lunch): ?>
                                <div>
                                    <?php if ($card_class === 'free'): ?>
                                        <form method="POST">
                                            <input type="hidden" name="date" value="<?php echo $selected_date; ?>">
                                            <input type="hidden" name="slot" value="<?php echo $slot['full_range']; ?>">
                                            <input type="hidden" name="action" value="block_slot">
                                            <button type="submit" class="btn btn-outline-danger btn-sm rounded-pill">Block for Admin</button>
                                        </form>
                                    <?php elseif ($card_class === 'blocked'): ?>
                                        <form method="POST">
                                            <input type="hidden" name="date" value="<?php echo $selected_date; ?>">
                                            <input type="hidden" name="slot" value="<?php echo $booking['time_slot']; ?>">
                                            <input type="hidden" name="action" value="unblock_slot">
                                            <button type="submit" class="btn btn-outline-success btn-sm rounded-pill">Remove Admin Block</button>
                                        </form>
                                    <?php elseif ($card_class === 'pending'): ?>
                                        <form method="POST">
                                            <input type="hidden" name="date" value="<?php echo $selected_date; ?>">
                                            <input type="hidden" name="slot" value="<?php echo $booking['time_slot']; ?>">
                                            <input type="hidden" name="action" value="confirm_pending">
                                            <button type="submit" class="btn btn-danger btn-sm rounded-pill shadow-sm">Confirm & Paid</button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <?php if ($booking && $booking['user_name'] !== 'Admin'): ?>
                             <div class="mt-3 p-2 bg-light rounded">
                                <small class="d-block"><strong>Name:</strong> <?php echo htmlspecialchars($booking['user_name']); ?></small>
                                <small class="d-block"><strong>Mobile:</strong> <?php echo htmlspecialchars($booking['user_mobile']); ?></small>
                                <small class="d-block"><strong>Payment:</strong> <?php echo strtoupper($booking['status'] === 'confirmed' ? 'Paid' : 'Unpaid'); ?></small>
                                <small class="d-block"><strong>Booked On:</strong> <?php echo date('d M, h:i A', strtotime($booking['created_at'])); ?></small>
                            </div>
                        <?php elseif ($booking && $booking['user_name'] === 'Admin'): ?>
                            <div class="mt-3 p-2 bg-light rounded border-start border-3 border-secondary">
                                <small class="d-block"><strong>By:</strong> Admin</small>
                                <small class="d-block"><strong>Slot:</strong> <?php echo htmlspecialchars($booking['time_slot']); ?></small>
                                <small class="d-block"><strong>Status:</strong> Confirmed & Paid</small>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <?php 
                // Collect and show appointments that didn't match any slot
                $unmapped = [];
                foreach ($bookings as $time_key => $slot_bookings) {
                    $found = false;
                    foreach ($slots as $s) if($s['time'] === $time_key) $found = true;
                    if (!$found) $unmapped = array_merge($unmapped, $slot_bookings);
                }
            ?>

            <?php if (!empty($unmapped)): ?>
                <div class="mt-5">
                    <h4 class="text-muted mb-3"><i class="fas fa-exclamation-triangle me-2"></i>Unmapped Appointments (<?php echo count($unmapped); ?>)</h4>
                    <div class="row">
                        <?php foreach ($unmapped as $b): ?>
                            <div class="col-md-4">
                                <div class="card mb-3 border-danger shadow-sm">
                                    <div class="card-body">
                                        <h6 class="card-title"><?php echo htmlspecialchars($b['time_slot']); ?></h6>
                                        <p class="card-text mb-1"><strong><?php echo htmlspecialchars($b['user_name']); ?></strong></p>
                                        <small class="text-muted d-block"><?php echo htmlspecialchars($b['user_mobile']); ?></small>
                                        <span class="badge bg-danger mt-2"><?php echo ucfirst($b['status']); ?></span>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i> Above appointments have time formats that don't match the current slot settings.
                    </div>
                </div>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<script>
    // Auto-hide alerts
    setTimeout(function() {
        let alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            let bsAlert = new bootstrap.Alert(alert);
            if (bsAlert) bsAlert.close();
        });
    }, 5000);
</script>

<?php
$content = ob_get_clean();
include 'layout.php';
?>
