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

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

include 'header.php';

$user_id = $_SESSION['user_id'];
$db = db();

// Fetch user's orders
$stmt = $db->prepare("SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$orders = $stmt->fetchAll();

?>

<div class="container mt-5">
    <h2>My Order History</h2>
    <hr>

    <?php
    if (isset($_SESSION['success_message'])) {
        echo '<div class="alert alert-success">' . $_SESSION['success_message'] . '</div>';
        unset($_SESSION['success_message']);
    }
    if (isset($_SESSION['error_message'])) {
        echo '<div class="alert alert-danger">' . $_SESSION['error_message'] . '</div>';
        unset($_SESSION['error_message']);
    }
    ?>

    <?php if (empty($orders)): ?>
        <div class="alert alert-info">You have not placed any orders yet.</div>
    <?php else: ?>
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Order ID</th>
                    <th>Date</th>
                    <th>Total</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orders as $order): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($order['id']); ?></td>
                        <td><?php echo htmlspecialchars(date('F j, Y, g:i a', strtotime($order['created_at']))); ?></td>
                        <td>$<?php echo htmlspecialchars(number_format($order['total_price'], 2)); ?></td>
                        <td><?php echo htmlspecialchars(ucfirst($order['status'])); ?></td>
                        <td>
                            <a href="order_status.php?order_id=<?php echo $order['id']; ?>" class="btn btn-info btn-sm">View Details / Track</a>
                            <?php
                            // Check if a review has already been submitted for this order
                            $stmt_rating = $db->prepare("SELECT id FROM ratings WHERE order_id = ?");
                            $stmt_rating->execute([$order['id']]);
                            $existing_rating = $stmt_rating->fetch();

                            // If order is delivered and no review exists, show the 'Leave a Review' link
                            if ($order['status'] === 'Delivered' && !$existing_rating):
                            ?>
                                <a href="leave_review.php?order_id=<?php echo $order['id']; ?>" class="btn btn-success btn-sm mt-1">Leave a Review</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

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