<?php
require_once __DIR__ . '/includes/auth.php';
requireLogin();

$user = getCurrentUser();

if ($user['user_type'] === 'admin') {
    redirectToDashboard();
}

$conn = getDBConnection();
$stmt = $conn->prepare("
    SELECT b.*, s.name as service_name, s.price, s.duration, s.category, p.status as payment_status, p.transaction_id, p.payment_method, p.payment_date
    FROM bookings b
    JOIN services s ON b.service_id = s.id
    LEFT JOIN payments p ON b.id = p.booking_id
    WHERE b.user_id = ?
    ORDER BY b.created_at DESC
");
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
$bookings_result = $stmt->get_result();
$bookings = [];
while ($row = $bookings_result->fetch_assoc()) {
    $bookings[] = $row;
}
$stmt->close();
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Oldage Home</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.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <?php include 'includes/header.php'; ?>

    <section class="py-5">
        <div class="container">
            <div class="row">
                <div class="col">
                    <h1 class="mb-4">Welcome back, <?php echo htmlspecialchars($user['name']); ?>!</h1>
                    <p class="lead mb-5">Manage your bookings and account information</p>
                </div>
            </div>

            <div class="row">
                <div class="col-lg-4 mb-4">
                    <div class="card">
                        <div class="card-body text-center">
                            <i class="fas fa-user-circle fa-3x text-primary mb-3"></i>
                            <h5>Account Information</h5>
                            <p><strong>Name:</strong> <?php echo htmlspecialchars($user['name']); ?></p>
                            <p><strong>Email:</strong> <?php echo htmlspecialchars($user['email']); ?></p>
                            <p><strong>Phone:</strong> <?php echo htmlspecialchars($user['phone'] ?? 'Not provided'); ?></p>
                            <p><strong>Account Type:</strong> <?php echo ucfirst($user['user_type']); ?></p>
                            <a href="profile.php" class="btn btn-outline-primary btn-sm">Edit Profile</a>
                        </div>
                    </div>
                </div>

                <div class="col-lg-8">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">My Bookings</h5>
                            <a href="book-services.php" class="btn btn-primary btn-sm">Book New Service</a>
                        </div>
                        <div class="card-body">
                            <?php if (empty($bookings)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                                    <h6 class="text-muted">No bookings yet</h6>
                                    <p class="text-muted">Start by booking one of our services</p>
                                    <a href="book-services.php" class="btn btn-primary">Browse Services</a>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Service</th>
                                                <th>Date & Time</th>
                                                <th>Amount</th>
                                                <th>Status</th>
                                                <th>Payment</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($bookings as $booking): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($booking['service_name']); ?></td>
                                                <td>
                                                    <?php echo date('M j, Y', strtotime($booking['booking_date'])); ?><br>
                                                    <small class="text-muted"><?php echo date('g:i A', strtotime($booking['booking_time'])); ?></small>
                                                </td>
                                                <td>$<?php echo number_format($booking['total_amount'], 2); ?></td>
                                                <td>
                                                    <?php
                                                    $status_class = match($booking['status']) {
                                                        'pending' => 'warning',
                                                        'confirmed' => 'success',
                                                        'completed' => 'info',
                                                        'cancelled' => 'danger',
                                                        default => 'secondary'
                                                    };
                                                    ?>
                                                    <span class="badge bg-<?php echo $status_class; ?>">
                                                        <?php echo ucfirst($booking['status']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?php if ($booking['payment_status'] === 'completed'): ?>
                                                        <span class="badge bg-success">Paid</span>
                                                    <?php elseif ($booking['payment_status'] === 'pending'): ?>
                                                        <span class="badge bg-warning">Pending</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-danger">Failed</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($booking['status'] === 'pending' && $booking['payment_status'] !== 'completed'): ?>
                                                        <a href="payment.php?booking_id=<?php echo $booking['id']; ?>" class="btn btn-sm btn-success">Pay Now</a>
                                                    <?php endif; ?>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="viewBookingDetails(<?php echo $booking['id']; ?>)">Details</button>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <div class="modal fade" id="bookingModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Booking Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="bookingDetails"></div>
            </div>
        </div>
    </div>

    <script>
    const bookings = <?php echo json_encode($bookings, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); ?>;

    function escapeHtml(value) {
        return String(value ?? '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function formatLabel(value) {
        if (!value) return 'Not available';
        return value.charAt(0).toUpperCase() + value.slice(1);
    }

    function viewBookingDetails(bookingId) {
        const booking = bookings.find(item => Number(item.id) === Number(bookingId));
        const modal = new bootstrap.Modal(document.getElementById('bookingModal'));

        if (!booking) {
            document.getElementById('bookingDetails').innerHTML = '<div class="alert alert-danger mb-0">Booking details could not be found.</div>';
            modal.show();
            return;
        }

        const paymentStatus = booking.payment_status ? formatLabel(booking.payment_status) : 'Not started';
        const transactionId = booking.transaction_id ? escapeHtml(booking.transaction_id) : 'Not available';
        const paymentMethod = booking.payment_method ? escapeHtml(booking.payment_method.replace('_', ' ')) : 'Not available';
        const paymentDate = booking.payment_date ? escapeHtml(booking.payment_date) : 'Not available';
        const notes = booking.notes ? escapeHtml(booking.notes) : 'No special notes added.';

        document.getElementById('bookingDetails').innerHTML = `
            <div class="row g-4">
                <div class="col-md-6">
                    <div class="p-3 bg-light rounded-3 h-100">
                        <h6 class="fw-bold mb-3">Service Information</h6>
                        <p class="mb-2"><strong>Booking ID:</strong> #${String(booking.id).padStart(6, '0')}</p>
                        <p class="mb-2"><strong>Service:</strong> ${escapeHtml(booking.service_name)}</p>
                        <p class="mb-2"><strong>Category:</strong> ${escapeHtml(booking.category ?? 'General')}</p>
                        <p class="mb-2"><strong>Duration:</strong> ${escapeHtml(booking.duration ?? 'Not available')}</p>
                        <p class="mb-0"><strong>Amount:</strong> $${Number(booking.total_amount).toFixed(2)}</p>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="p-3 bg-light rounded-3 h-100">
                        <h6 class="fw-bold mb-3">Booking Status</h6>
                        <p class="mb-2"><strong>Date:</strong> ${escapeHtml(booking.booking_date)}</p>
                        <p class="mb-2"><strong>Time:</strong> ${escapeHtml(booking.booking_time)}</p>
                        <p class="mb-2"><strong>Booking Status:</strong> ${escapeHtml(formatLabel(booking.status))}</p>
                        <p class="mb-2"><strong>Payment Status:</strong> ${escapeHtml(paymentStatus)}</p>
                        <p class="mb-0"><strong>Created At:</strong> ${escapeHtml(booking.created_at)}</p>
                    </div>
                </div>
                <div class="col-12">
                    <div class="p-3 border rounded-3">
                        <h6 class="fw-bold mb-3">Payment Details</h6>
                        <div class="row g-3">
                            <div class="col-md-4"><strong>Method:</strong><br>${paymentMethod}</div>
                            <div class="col-md-4"><strong>Transaction ID:</strong><br>${transactionId}</div>
                            <div class="col-md-4"><strong>Payment Date:</strong><br>${paymentDate}</div>
                        </div>
                    </div>
                </div>
                <div class="col-12">
                    <div class="p-3 border rounded-3">
                        <h6 class="fw-bold mb-2">Special Notes</h6>
                        <p class="mb-0">${notes}</p>
                    </div>
                </div>
            </div>
        `;

        modal.show();
    }
    </script>

    <?php include 'includes/footer.php'; ?>

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

