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

// Admin authentication
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Handle status update via AJAX or POST
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['appointment_id']) && isset($_POST['action'])) {
    $app_id = intval($_POST['appointment_id']);
    $action = $_POST['action'];
    $reason = $_POST['reason'] ?? '';
    $new_status = '';
    if ($action == 'approve') $new_status = 'confirmed';
    elseif ($action == 'complete') $new_status = 'completed';
    elseif ($action == 'cancel') $new_status = 'cancelled';
    
    if ($new_status) {
        $conn->query("UPDATE opd_appointments SET status = '$new_status' WHERE id = $app_id");
        if ($action == 'approve') {
            $conn->query("UPDATE opd_appointments SET approved_by = {$_SESSION['admin_id']}, approved_at = NOW() WHERE id = $app_id");
        } elseif ($action == 'cancel') {
            $conn->query("UPDATE opd_appointments SET cancelled_at = NOW(), cancellation_reason = '" . $conn->real_escape_string($reason) . "' WHERE id = $app_id");
        }
        // Send SMS to patient
        $app = $conn->query("SELECT patient_id FROM opd_appointments WHERE id = $app_id")->fetch_assoc();
        $patient = $conn->query("SELECT mobile FROM opd_patients WHERE id = {$app['patient_id']}")->fetch_assoc();
        if ($patient) {
            $msg = "Your appointment #$app_id status changed to $new_status. Dr. Ferdous";
            sendSMSViaBulkSMSBD($patient['mobile'], $msg);
        }
    }
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        echo json_encode(['success' => true]);
        exit;
    } else {
        header("Location: dashboard.php");
        exit;
    }
}

// Get filter values
$chamber_filter = $_GET['chamber'] ?? '';
$status_filter = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

// Build WHERE clause
$where = "WHERE 1=1";
if ($chamber_filter) $where .= " AND a.chamber_id = " . intval($chamber_filter);
if ($status_filter) $where .= " AND a.status = '$status_filter'";
if ($date_from) $where .= " AND a.appointment_date >= '$date_from'";
if ($date_to) $where .= " AND a.appointment_date <= '$date_to'";

// Fetch appointments with safe time handling
$query = "SELECT a.*, p.name as patient_name, p.mobile as patient_mobile, 
                 c.name as chamber_name, ts.start_time, ts.end_time
          FROM opd_appointments a
          JOIN opd_patients p ON a.patient_id = p.id
          JOIN chambers c ON a.chamber_id = c.id
          LEFT JOIN time_slots ts ON a.time_slot_id = ts.id
          $where
          ORDER BY a.appointment_date DESC, ts.start_time ASC";
$appointments = $conn->query($query);

// Calculate stats
$stats = $conn->query("SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) as confirmed,
    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled,
    SUM(fee) as total_fee
    FROM opd_appointments a $where")->fetch_assoc();

$chambers = $conn->query("SELECT id, name FROM chambers WHERE status='active'");
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard | Dr. Ferdous</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #2d6a4f; --primary-dark: #1b4332; --primary-light: #52b788; }
        * { font-family: 'Poppins', sans-serif; }
        body { background: #f0f2f5; }
        .sidebar { background: linear-gradient(135deg, #1b4332, #2d6a4f); min-height: 100vh; position: fixed; width: 260px; transition: all 0.3s; z-index: 1000; }
        .sidebar .nav-link { color: rgba(255,255,255,0.8); padding: 12px 20px; margin: 5px 10px; border-radius: 10px; transition: all 0.3s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: rgba(255,255,255,0.2); color: white; transform: translateX(5px); }
        .main-content { margin-left: 260px; padding: 20px; transition: all 0.3s; }
        .stat-card { background: white; border-radius: 20px; padding: 20px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); transition: transform 0.3s, box-shadow 0.3s; cursor: pointer; }
        .stat-card:hover { transform: translateY(-5px); box-shadow: 0 15px 30px rgba(0,0,0,0.1); }
        .stat-icon { font-size: 2.5rem; opacity: 0.2; position: absolute; right: 20px; top: 20px; }
        .table-container { background: white; border-radius: 20px; padding: 20px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); }
        .filter-card { background: white; border-radius: 20px; padding: 15px 20px; margin-bottom: 20px; }
        .btn-gradient { background: linear-gradient(135deg, var(--primary), var(--primary-light)); border: none; color: white; }
        .status-badge { padding: 5px 12px; border-radius: 30px; font-size: 12px; font-weight: 600; }
        .status-pending { background: #ffc107; color: #000; }
        .status-confirmed { background: #28a745; color: #fff; }
        .status-completed { background: #17a2b8; color: #fff; }
        .status-cancelled { background: #dc3545; color: #fff; }
        @keyframes fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        .animate { animation: fadeInUp 0.5s ease forwards; }
    </style>
</head>
<body>
<div class="sidebar">
    <div class="text-center py-4">
        <h4 class="text-white">🏥 Dr. Ferdous</h4>
        <small class="text-white-50">Admin Panel</small>
    </div>
    <hr class="bg-light">
    <nav class="nav flex-column">
        <a href="dashboard.php" class="nav-link active"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a>
        <a href="#" id="refreshBtn" class="nav-link"><i class="fas fa-sync-alt me-2"></i> Refresh</a>
        <a href="logout.php" class="nav-link"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
    </nav>
</div>

<div class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3><i class="fas fa-calendar-check me-2"></i> Appointment Management</h3>
        <div>Welcome, <?= htmlspecialchars($_SESSION['admin_name'] ?? 'Admin') ?></div>
    </div>

    <!-- Statistics Cards -->
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-sm-6">
            <div class="stat-card position-relative" onclick="location.href='?status=all'">
                <h2><?= $stats['total'] ?></h2>
                <p class="text-muted mb-0">Total Appointments</p>
                <div class="stat-icon"><i class="fas fa-calendar"></i></div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="stat-card position-relative" onclick="location.href='?status=pending'">
                <h2><?= $stats['pending'] ?></h2>
                <p class="text-muted mb-0">Pending</p>
                <div class="stat-icon"><i class="fas fa-clock"></i></div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="stat-card position-relative" onclick="location.href='?status=confirmed'">
                <h2><?= $stats['confirmed'] ?></h2>
                <p class="text-muted mb-0">Confirmed</p>
                <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="stat-card position-relative" onclick="location.href='?status=completed'">
                <h2><?= $stats['completed'] ?></h2>
                <p class="text-muted mb-0">Completed</p>
                <div class="stat-icon"><i class="fas fa-flag-checkered"></i></div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="filter-card">
        <form method="get" class="row g-3" id="filterForm">
            <div class="col-md-3">
                <label class="form-label">Chamber</label>
                <select name="chamber" class="form-control">
                    <option value="">All Chambers</option>
                    <?php while($ch = $chambers->fetch_assoc()): ?>
                        <option value="<?= $ch['id'] ?>" <?= ($chamber_filter == $ch['id']) ? 'selected' : '' ?>><?= htmlspecialchars($ch['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Status</label>
                <select name="status" class="form-control">
                    <option value="">All</option>
                    <option value="pending" <?= $status_filter=='pending'?'selected':'' ?>>Pending</option>
                    <option value="confirmed" <?= $status_filter=='confirmed'?'selected':'' ?>>Confirmed</option>
                    <option value="completed" <?= $status_filter=='completed'?'selected':'' ?>>Completed</option>
                    <option value="cancelled" <?= $status_filter=='cancelled'?'selected':'' ?>>Cancelled</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?= $date_from ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?= $date_to ?>">
            </div>
            <div class="col-md-3 d-flex align-items-end">
                <button type="submit" class="btn btn-primary me-2"><i class="fas fa-filter"></i> Filter</button>
                <a href="dashboard.php" class="btn btn-secondary"><i class="fas fa-undo"></i> Reset</a>
            </div>
        </form>
    </div>

    <!-- Appointments Table -->
    <div class="table-container">
        <div class="table-responsive">
            <table class="table table-hover align-middle" id="appointmentsTable">
                <thead class="table-light">
                    <tr>
                        <th>ID</th><th>Patient</th><th>Mobile</th><th>Chamber</th><th>Date</th><th>Time</th><th>Category</th><th>Fee</th><th>Status</th><th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($appointments && $appointments->num_rows > 0): ?>
                        <?php while($row = $appointments->fetch_assoc()): 
                            // Safe time display
                            $time_display = '—';
                            if (!empty($row['start_time']) && !empty($row['end_time'])) {
                                $start = date('h:i A', strtotime($row['start_time']));
                                $end = date('h:i A', strtotime($row['end_time']));
                                $time_display = $start . ' - ' . $end;
                            } elseif (!empty($row['start_time'])) {
                                $time_display = date('h:i A', strtotime($row['start_time'])) . ' (To be confirmed)';
                            }
                            $category_label = ucfirst(str_replace('_', ' ', $row['patient_category']));
                            $fee = number_format($row['fee'], 2);
                            $status_class = 'status-' . $row['status'];
                        ?>
                        <tr class="animate" style="animation-delay: <?= rand(0, 10)*0.02 ?>s">
                            <td><?= $row['id'] ?></td>
                            <td><?= htmlspecialchars($row['patient_name']) ?></td>
                            <td><?= $row['patient_mobile'] ?></td>
                            <td><?= htmlspecialchars($row['chamber_name']) ?></td>
                            <td><?= date('d M Y', strtotime($row['appointment_date'])) ?></td>
                            <td><?= $time_display ?></td>
                            <td><?= $category_label ?></td>
                            <td>৳<?= $fee ?></td>
                            <td><span class="status-badge <?= $status_class ?>"><?= ucfirst($row['status']) ?></span></td>
                            <td>
                                <?php if($row['status'] == 'pending'): ?>
                                    <button class="btn btn-sm btn-success update-status" data-id="<?= $row['id'] ?>" data-action="approve"><i class="fas fa-check"></i> Approve</button>
                                    <button class="btn btn-sm btn-danger update-status" data-id="<?= $row['id'] ?>" data-action="cancel" data-bs-toggle="modal" data-bs-target="#cancelModal" data-reason="">Cancel</button>
                                <?php elseif($row['status'] == 'confirmed'): ?>
                                    <button class="btn btn-sm btn-info update-status" data-id="<?= $row['id'] ?>" data-action="complete"><i class="fas fa-check-double"></i> Complete</button>
                                    <button class="btn btn-sm btn-danger update-status" data-id="<?= $row['id'] ?>" data-action="cancel" data-bs-toggle="modal" data-bs-target="#cancelModal">Cancel</button>
                                <?php elseif($row['status'] == 'completed'): ?>
                                    <span class="text-muted">Completed</span>
                                <?php elseif($row['status'] == 'cancelled'): ?>
                                    <span class="text-muted">Cancelled</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="10" class="text-center py-4">No appointments found</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Cancel Modal -->
<div class="modal fade" id="cancelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Cancel Appointment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <label>Reason for cancellation</label>
                <textarea id="cancelReason" class="form-control" rows="3"></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" id="confirmCancel" class="btn btn-danger">Confirm Cancel</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function() {
        let currentAppointmentId = null;
        // Handle status update buttons
        $('.update-status').click(function(e) {
            let action = $(this).data('action');
            let id = $(this).data('id');
            if (action !== 'cancel') {
                e.preventDefault();
                if (confirm(`Are you sure to ${action} this appointment?`)) {
                    $.post(window.location.href, { appointment_id: id, action: action }, function(res) {
                        location.reload();
                    }).fail(() => alert('Error updating status'));
                }
            } else {
                currentAppointmentId = id;
                $('#cancelModal').modal('show');
            }
        });
        $('#confirmCancel').click(function() {
            let reason = $('#cancelReason').val();
            if (!reason) {
                alert('Please provide a reason for cancellation');
                return;
            }
            $.post(window.location.href, { appointment_id: currentAppointmentId, action: 'cancel', reason: reason }, function(res) {
                location.reload();
            }).fail(() => alert('Error cancelling'));
        });
        $('#refreshBtn').click(function(e) {
            e.preventDefault();
            location.reload();
        });
    });
</script>
</body>
</html>