<?php
// Check if user is logged in
require_once 'includes/config.php';
require_once 'includes/functions.php';
if (!isLoggedIn()) {
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    redirect(SITE_URL . '/auth/login.php');
}

// Handle order deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_order'])) {
    $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
    
    if ($order_id > 0) {
        try {
            // Verify the order belongs to the current user
            $stmt = $pdo->prepare("SELECT user_id FROM orders WHERE id = ?");
            $stmt->execute([$order_id]);
            $order = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($order && $order['user_id'] == $_SESSION['user_id']) {
                // Delete the order (will cascade to order_items)
                $stmt = $pdo->prepare("DELETE FROM orders WHERE id = ?");
                $stmt->execute([$order_id]);
                $_SESSION['success_message'] = "تم حذف الطلب بنجاح.";
            } else {
                $_SESSION['error_message'] = "الطلب غير موجود أو ليس لديك الصلاحية لحذفه.";
            }
        } catch (Exception $e) {
            $_SESSION['error_message'] = "خطأ في حذف الطلب: " . $e->getMessage();
        }
    } else {
        $_SESSION['error_message'] = "معرف الطلب غير صالح.";
    }
    
    // Redirect to refresh the page
    redirect(SITE_URL . '/orders.php');
}

require_once 'includes/header.php';

// Get user's orders
$stmt = $pdo->prepare("
    SELECT o.*, u.username, u.email 
    FROM orders o 
    JOIN users u ON o.user_id = u.id 
    WHERE o.user_id = ?
    ORDER BY o.order_date DESC
");
$stmt->execute([$_SESSION['user_id']]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container">
    <div class="section-title">
        <h2>سجل طلباتي</h2>
    </div>
    
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="message success">
            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="message error">
            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
        </div>
    <?php endif; ?>
    
    <?php if (empty($orders)): ?>
        <div class="empty-products">
            <i class="fas fa-shopping-cart"></i>
            <h3>لم يتم العثور على طلبات</h3>
            <p>لم تقم بوضع أي طلبات بعد.</p>
            <a href="<?php echo SITE_URL; ?>/products/index.php" class="btn btn-primary">ابدأ التسوق</a>
        </div>
    <?php else: ?>
        <div class="cart-table">
            <table>
                <thead>
                    <tr>
                        <th>معرف الطلب</th>
                        <th>التاريخ</th>
                        <th>المبلغ الإجمالي</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $order): ?>
                        <tr>
                            <td>#<?php echo $order['id']; ?></td>
                            <td><?php echo date('j M Y', strtotime($order['order_date'])); ?></td>
                            <td>$<?php echo number_format($order['total_amount'], 2); ?></td>
                            <td>
                                <a href="<?php echo SITE_URL; ?>/invoice.php?id=<?php echo $order['id']; ?>" target="_blank" class="btn btn-outline btn-small">عرض الفاتورة</a>
                                <form method="POST" action="" style="display: inline-block;" onsubmit="return confirm('هل أنت متأكد أنك تريد حذف هذا الطلب؟ لا يمكن التراجع عن هذا الإجراء.');">
                                    <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                    <button type="submit" name="delete_order" class="btn btn-danger btn-small">حذف</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<style>
.cart-table {
    direction: rtl;
    text-align: right;
}

.cart-table th,
.cart-table td {
    text-align: right;
}

.section-title {
    direction: rtl;
    text-align: center;
}

.empty-products {
    direction: rtl;
    text-align: center;
}
</style>

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