<?php
require_once __DIR__ . '/auth.php';
if (empty($_SESSION['user'])) {
    header('Location: login.php');
    exit;
}
$user = $_SESSION['user'];
$message = '';
$bookingSuccess = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['profile_update'])) {
        $firstName = trim($_POST['first_name'] ?? '');
        $lastName = trim($_POST['last_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        if ($firstName === '' || $lastName === '' || $email === '') {
            $message = 'Please fill in all profile fields.';
        } else {
            $updated = updateUserProfile($user['email'], [
                'first_name' => $firstName,
                'last_name' => $lastName,
                'email' => $email
            ]);
            if ($updated) {
                $_SESSION['user'] = $updated;
                $user = $updated;
                $message = 'Profile updated successfully.';
            } else {
                $message = 'Unable to update profile.';
            }
        }
    }
    if (isset($_POST['booking_request'])) {
        $destination = trim($_POST['destination'] ?? '');
        $departure = trim($_POST['departure_date'] ?? '');
        $returnDate = trim($_POST['return_date'] ?? '');
        $passengers = trim($_POST['passengers'] ?? '1');
        $notes = trim($_POST['notes'] ?? '');
        if ($destination === '' || $departure === '') {
            $message = 'Please provide destination and departure date.';
        } else {
            addBooking([
                'agent_email' => $user['email'],
                'destination' => $destination,
                'departure_date' => $departure,
                'return_date' => $returnDate,
                'passengers' => $passengers,
                'notes' => $notes,
                'status' => 'Pending',
                'assigned_to' => 'Main Agent Team'
            ]);
            $bookingSuccess = 'Your flight request was sent to the main agent. We will update you soon.';
        }
    }
}
$bookings = getBookings($user['email']);
?>
<!DOCTYPE html>
<html lang="en-US">
<?php include "pages/header.php"; ?>

<div id="page-title" class="text-grey background-overlay background-img-dark" style="background-image: url('images/page-title-9.jpg');">
    <div class="text-center">
        <ol class="breadcrumb z-index-2 position-relative no-background padding-30px margin-0px border-top-1 border-grey-4">
            <li><a href="index.php" class="text-white">Home</a></li>
            <li class="active">Dashboard</li>
        </ol>
    </div>
</div>

<section class="padding-tb-80px background-white">
    <div class="container">
        <?php if ($message): ?>
            <div class="alert alert-info"><?= htmlentities($message) ?></div>
        <?php endif; ?>
        <?php if ($bookingSuccess): ?>
            <div class="alert alert-success"><?= htmlentities($bookingSuccess) ?></div>
        <?php endif; ?>

        <div class="row">
            <div class="col-lg-4 mb-4">
                <div class="dashboard-panel">
                    <h3>Agent details</h3>
                    <p><strong>Name:</strong> <?= htmlentities($user['first_name'] . ' ' . $user['last_name']) ?></p>
                    <p><strong>Email:</strong> <?= htmlentities($user['email']) ?></p>
                    <p><strong>Joined:</strong> <?= htmlentities(date('M d, Y', strtotime($user['created_at']))) ?></p>
                    <p class="small-text">Use this panel to update your profile and submit flight requests directly to the main agent.</p>
                    <button type="button" class="btn btn-primary btn-block mt-3" data-toggle="modal" data-target="#bookingModal">Send flight request</button>
                </div>
                <div class="dashboard-panel">
                    <h3>Quick stats</h3>
                    <div class="dashboard-summary">
                        <div class="card mb-3">
                            <div class="card-body">
                                <h5 class="card-title">Total bookings</h5>
                                <div class="display-4"><?= count($bookings) ?></div>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">Last request</h5>
                                <p class="mb-0"><?= htmlentities($bookings ? $bookings[0]['destination'] : 'No requests yet') ?></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-8 mb-4">
                <div class="dashboard-panel">
                    <h3>Profile update</h3>
                    <form action="dashboard.php" method="post">
                        <input type="hidden" name="profile_update" value="1">
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label>First name</label>
                                <input type="text" name="first_name" class="form-control" value="<?= htmlentities($user['first_name']) ?>" required>
                            </div>
                            <div class="form-group col-md-6">
                                <label>Last name</label>
                                <input type="text" name="last_name" class="form-control" value="<?= htmlentities($user['last_name']) ?>" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Email address</label>
                            <input type="email" name="email" class="form-control" value="<?= htmlentities($user['email']) ?>" required>
                        </div>
                        <button type="submit" class="btn btn-light">Save profile</button>
                    </form>
                </div>
                <div class="dashboard-panel booking-table">
                    <h3>Booking requests</h3>
                    <?php if (count($bookings) === 0): ?>
                        <p class="small-text">You have not sent any flight requests yet. Use the button above to send your first request.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-borderless">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Destination</th>
                                        <th>Departure</th>
                                        <th>Status</th>
                                        <th>Created</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($bookings as $booking): ?>
                                        <tr>
                                            <td><?= htmlentities($booking['id']) ?></td>
                                            <td><?= htmlentities($booking['destination']) ?></td>
                                            <td><?= htmlentities($booking['departure_date']) ?></td>
                                            <td><span class="badge badge-<?= strtolower($booking['status']) ?>"><?= htmlentities($booking['status']) ?></span></td>
                                            <td><?= htmlentities(date('M d, Y', strtotime($booking['created_at']))) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Booking request modal -->
<div class="modal fade" id="bookingModal" tabindex="-1" role="dialog" aria-labelledby="bookingModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="bookingModalLabel">Send flight booking request</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form action="dashboard.php" method="post">
                <input type="hidden" name="booking_request" value="1">
                <div class="modal-body">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label>Destination</label>
                            <input type="text" name="destination" class="form-control" placeholder="Destination city or route" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label>Passengers</label>
                            <input type="number" name="passengers" class="form-control" value="1" min="1" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label>Departure date</label>
                            <input type="date" name="departure_date" class="form-control" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label>Return date</label>
                            <input type="date" name="return_date" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Notes for main agent</label>
                        <textarea name="notes" rows="4" class="form-control" placeholder="Add travel details, preferred airlines or budget."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Send request</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include "pages/footer.php"; ?>

<script src="//<?= $_SERVER['HTTP_HOST']; ?>/travelsspeed/js/popper.min.js"></script>
<script src="//<?= $_SERVER['HTTP_HOST']; ?>/travelsspeed/js/bootstrap.min.js"></script>
</body>
</html>
