<?php
session_start();

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

include 'db.php';

try {
    $userStmt = $pdo->prepare("SELECT id FROM users WHERE username = :u");
    $userStmt->execute([':u' => $_SESSION['user']]);
    $currentUser = $userStmt->fetch(PDO::FETCH_ASSOC);
    $userId = $currentUser ? $currentUser['id'] : 0;

    $stmt = $pdo->prepare("SELECT * FROM orders WHERE user_id = :uid ORDER BY created_at DESC");
    $stmt->execute([':uid' => $userId]);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $orders = [];
}

include 'header.php';
?>

<style>
    h2 { color:#2c3e50; font-size:18px; }
    .back-link { display:inline-block; margin-bottom:15px; color:#2980b9; text-decoration:none; font-size:14px; }
    .orders-table { width:100%; border-collapse:collapse; background:white; border-radius:8px; overflow:hidden; box-shadow:0 1px 4px rgba(0,0,0,0.1); }
    .orders-table th { background:#2c3e50; color:white; padding:11px 15px; text-align:right; font-size:14px; }
    .orders-table td { padding:10px 15px; font-size:13px; border-bottom:1px solid #eee; vertical-align:middle; }
    .orders-table tr:last-child td { border-bottom:none; }
    .receipt-thumb { width:60px; height:60px; object-fit:cover; border-radius:5px; }
    .no-order { text-align:center; color:#999; padding:30px; }
</style>

<a href="index.php" class="back-link">→ بازگشت به فروشگاه</a>
<h2>📋 سفارشات من — <?php echo htmlspecialchars($_SESSION['user']); ?></h2>

<?php if (count($orders) == 0): ?>
    <p class="no-order">هنوز سفارشی ثبت نکرده‌اید.</p>
<?php else: ?>
<table class="orders-table">
    <tr><th>#</th><th>کتاب‌ها</th><th>فیش</th><th>تاریخ</th></tr>
    <?php $i = 1; foreach ($orders as $order): ?>
    <tr>
        <td><?php echo $i++; ?></td>
        <td><?php echo $order['books']; ?></td>
        <td><a href="<?php echo $order['receipt_img']; ?>" target="_blank">
            <img src="<?php echo $order['receipt_img']; ?>" class="receipt-thumb" alt="فیش">
        </a></td>
        <td><?php echo $order['created_at']; ?></td>
    </tr>
    <?php endforeach; ?>
</table>
<?php endif; ?>

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