<?php
session_start();

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

include 'db.php';

// یوزرآیدی از دیتابیس
$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;

if (!isset($_SESSION['cart'])) $_SESSION['cart'] = [];

// حذف از سبد
if (isset($_GET['remove'])) {
    foreach ($_SESSION['cart'] as $k => $item) {
        if ($item['title'] == $_GET['remove']) { unset($_SESSION['cart'][$k]); break; }
    }
    $_SESSION['cart'] = array_values($_SESSION['cart']);
    header('Location: cart.php');
    exit;
}

$message = "";

// ثبت سفارش
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['receipt'])) {
    $buyerName = trim($_POST['buyer_name']);
    $file = $_FILES['receipt'];

    if ($buyerName == "") {
        $message = "error:لطفاً نام خود را وارد کنید.";
    } elseif (count($_SESSION['cart']) == 0) {
        $message = "error:سبد خرید خالی است.";
    } elseif ($file['error'] != 0) {
        $message = "error:خطا در آپلود فایل.";
    } else {
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['jpg','jpeg','png'])) {
            $message = "error:فقط فایل‌های jpg و png مجاز هستند.";
        } else {
            try {
                if (!is_dir('receipts')) mkdir('receipts', 0755, true);
                $newName = 'receipts/' . time() . '_' . rand(1000,9999) . '.' . $ext;
                move_uploaded_file($file['tmp_name'], $newName);

                $booksList = implode('، ', array_column($_SESSION['cart'], 'title'));
                $stmt = $pdo->prepare("INSERT INTO orders (user_id, buyer_name, books, receipt_img) VALUES (:uid, :name, :books, :img)");
                $stmt->execute([':uid' => $userId, ':name' => $buyerName, ':books' => $booksList, ':img' => $newName]);

                $_SESSION['cart'] = [];
                $message = "success:سفارش شما با موفقیت ثبت شد!";
            } catch (Exception $e) {
                $message = "error:خطا در ثبت سفارش. لطفاً دوباره امتحان کنید.";
            }
        }
    }
}

$cart = $_SESSION['cart'];
include 'header.php';
?>

<style>
    h2 { color: #2c3e50; font-size: 18px; }
    .top-bar { display:flex; justify-content:space-between; align-items:center; margin-bottom:15px; }
    .back-link { color:#2980b9; text-decoration:none; font-size:14px; }
    .my-orders-link { color:#27ae60; text-decoration:none; font-size:14px; }
    .cart-table { width:100%; border-collapse:collapse; background:white; border-radius:8px; overflow:hidden; box-shadow:0 1px 4px rgba(0,0,0,0.1); margin-bottom:25px; }
    .cart-table th { background:#2c3e50; color:white; padding:11px 15px; text-align:right; font-size:14px; }
    .cart-table td { padding:10px 15px; font-size:14px; border-bottom:1px solid #eee; }
    .cart-table img { width:50px; height:65px; object-fit:cover; border-radius:4px; }
    .btn-remove { color:#e74c3c; text-decoration:none; font-size:13px; }
    .order-form { background:white; padding:20px 25px; border-radius:8px; box-shadow:0 1px 4px rgba(0,0,0,0.1); }
    .order-form h3 { margin-top:0; color:#2c3e50; font-size:16px; }
    .order-form input[type=text], .order-form input[type=file] {
        width:100%; padding:8px 12px; font-size:14px; font-family:Tahoma,sans-serif;
        border:1px solid #ccc; border-radius:5px; margin:6px 0 15px 0; box-sizing:border-box;
    }
    .btn-submit { padding:9px 22px; background:#27ae60; color:white; border:none; border-radius:5px; font-size:14px; font-family:Tahoma,sans-serif; cursor:pointer; }
    .btn-submit:hover { background:#1e8449; }
    .alert { padding:12px 18px; border-radius:6px; margin-bottom:20px; font-size:14px; }
    .alert-success { background:#d5f5e3; color:#1e8449; }
    .alert-error   { background:#fadbd8; color:#c0392b; }
    .empty-cart { text-align:center; color:#999; padding:30px; }
</style>

<div class="top-bar">
    <a href="index.php" class="back-link">→ بازگشت به فروشگاه</a>
    <a href="my_orders.php" class="my-orders-link">📋 سفارشات من</a>
</div>
<h2>🛒 سبد خرید</h2>

<?php if ($message != ""): ?>
    <?php list($type, $text) = explode(':', $message, 2); ?>
    <div class="alert alert-<?php echo $type; ?>"><?php echo $text; ?></div>
<?php endif; ?>

<?php if (count($cart) == 0): ?>
    <p class="empty-cart">سبد خرید خالی است.</p>
<?php else: ?>
<table class="cart-table">
    <tr><th>تصویر</th><th>نام کتاب</th><th>نویسنده</th><th>حذف</th></tr>
    <?php foreach ($cart as $item): ?>
    <tr>
        <td><img src="<?php echo $item['image']; ?>" alt=""></td>
        <td><?php echo $item['title']; ?></td>
        <td><?php echo $item['author']; ?></td>
        <td><a href="cart.php?remove=<?php echo urlencode($item['title']); ?>" class="btn-remove">حذف</a></td>
    </tr>
    <?php endforeach; ?>
</table>
<div class="order-form">
    <h3>📎 آپلود فیش واریزی</h3>
    <form method="POST" enctype="multipart/form-data">
        <label>نام خریدار:</label>
        <input type="text" name="buyer_name" value="<?php echo htmlspecialchars($_SESSION['user']); ?>">
        <label>تصویر فیش (jpg یا png):</label>
        <input type="file" name="receipt" accept=".jpg,.jpeg,.png">
        <button type="submit" class="btn-submit">✅ ثبت سفارش</button>
    </form>
</div>
<?php endif; ?>

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