<?php
include "session.php";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../db.php';


// Check if order ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: orders.php");
    exit();
}

$order_id = intval($_GET['id']);

// Fetch order details
$order_stmt = $pdo->prepare("
    SELECT o.*, os.name as status_name, dc.name as delivery_company_name, w.name as wilaya_name
    FROM orders o
    LEFT JOIN order_statuses os ON o.status_id = os.id
    LEFT JOIN delivery_companies dc ON o.delivery_company_id = dc.id
    LEFT JOIN wilayas w ON o.wilaya_id = w.id
    WHERE o.id = ?
");
$order_stmt->execute([$order_id]);
$order = $order_stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    $_SESSION['error'] = "Order not found";
    header("Location: orders.php");
    exit();
}

// Fetch order items
$items_stmt = $pdo->prepare("
    SELECT oi.*, p.name as product_name, pv.sku, p.price as original_price
    FROM order_items oi
    LEFT JOIN product_variants pv ON oi.product_variant_id = pv.id
    LEFT JOIN products p ON pv.product_id = p.id
    WHERE oi.order_id = ?
");
$items_stmt->execute([$order_id]);
$items = $items_stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate order total
$order_total = 0;
foreach ($items as $item) {
    $order_total += $item['quantity'] * $item['unit_price'];
}
?>

<!DOCTYPE html>
<html dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>تفاصيل الطلب #<?= $order_id ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #4361ee;
            --primary-light: #3f37c9;
            --secondary: #3a0ca3;
            --success: #4cc9f0;
            --danger: #f72585;
            --warning: #f8961e;
            --info: #4895ef;
            --dark: #212529;
            --light: #f8f9fa;
            --gray: #6c757d;
            --white: #ffffff;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Tajawal', sans-serif;
        }
        
        body {
            background-color: #f5f7fb;
            color: var(--dark);
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .header h1 {
            color: var(--primary);
            font-size: 28px;
            font-weight: 700;
        }
        
        .btn {
            padding: 8px 15px;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-size: 14px;
            border: none;
        }
        
        .btn-primary {
            background-color: var(--primary);
            color: white;
        }
        
        .btn-primary:hover {
            background-color: var(--primary-light);
        }
        
        .btn-back {
            background-color: var(--gray);
            color: white;
        }
        
        .btn-back:hover {
            background-color: #5a6268;
        }
        
        .card {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .order-info {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .info-group {
            margin-bottom: 15px;
        }
        
        .info-label {
            font-weight: 500;
            color: var(--gray);
            margin-bottom: 5px;
        }
        
        .info-value {
            font-size: 16px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        th, td {
            padding: 12px 15px;
            text-align: right;
            border-bottom: 1px solid #e0e0e0;
        }
        
        th {
            background-color: var(--primary);
            color: white;
            font-weight: 500;
        }
        
        .status-badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-pending {
            background-color: rgba(248, 150, 30, 0.1);
            color: var(--warning);
        }
        
        .status-sent {
            background-color: rgba(76, 201, 240, 0.1);
            color: var(--success);
        }
        
        .status-delivered {
            background-color: rgba(72, 149, 239, 0.1);
            color: var(--info);
        }
        
        .status-cancelled {
            background-color: rgba(247, 37, 133, 0.1);
            color: var(--danger);
        }
        
        .total-row {
            font-weight: 700;
            background-color: #f8f9fa;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        
        @media (max-width: 768px) {
            .order-info {
                grid-template-columns: 1fr;
            }
            
            th, td {
                padding: 8px 10px;
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
    <?php include 'sidebar.php'; ?>

    <div class="container">
        <div class="header">
            <h1><i class="fas fa-file-invoice"></i> تفاصيل الطلب #<?= $order_id ?></h1>
            <a href="orders.php" class="btn btn-back">
                <i class="fas fa-arrow-left"></i> رجوع إلى الطلبات
            </a>
        </div>
        
        <?php if (isset($_SESSION['message'])): ?>
            <div class="message">
                <i class="fas fa-check-circle"></i> <?= $_SESSION['message'] ?>
            </div>
            <?php unset($_SESSION['message']); ?>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error'])): ?>
            <div class="error">
                <i class="fas fa-exclamation-circle"></i> <?= $_SESSION['error'] ?>
            </div>
            <?php unset($_SESSION['error']); ?>
        <?php endif; ?>
        
        <div class="card">
            <h2 style="margin-bottom: 20px;">معلومات الطلب</h2>
            
            <div class="order-info">
                <div>
                    <div class="info-group">
                        <div class="info-label">حالة الطلب:</div>
                        <div class="info-value">
                            <span class="status-badge status-<?= strtolower($order['status_name']) ?>">
                                <?= $order['status_name'] ?>
                            </span>
                        </div>
                    </div>
                    
                    <div class="info-group">
                        <div class="info-label">تاريخ الطلب:</div>
                        <div class="info-value"><?= date('Y-m-d H:i', strtotime($order['order_date'])) ?></div>
                    </div>
                    
                    <div class="info-group">
                        <div class="info-label">طريقة التوصيل:</div>
                        <div class="info-value">
                            <?= $order['delivery_company_name'] ?? '--' ?>
                            (<?= $order['delivery_type'] == 'home' ? 'توصيل للمنزل' : 'توصيل للمكتب' ?>)
                        </div>
                    </div>
                    
                    <?php if ($order['tracking_number']): ?>
                    <div class="info-group">
                        <div class="info-label">رقم التتبع:</div>
                        <div class="info-value"><?= $order['tracking_number'] ?></div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($order['sent_date']): ?>
                    <div class="info-group">
                        <div class="info-label">تاريخ الإرسال:</div>
                        <div class="info-value"><?= date('Y-m-d H:i', strtotime($order['sent_date'])) ?></div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div>
                    <div class="info-group">
                        <div class="info-label">اسم العميل:</div>
                        <div class="info-value"><?= htmlspecialchars($order['customer_name']) ?></div>
                    </div>
                    
                    <div class="info-group">
                        <div class="info-label">رقم الهاتف:</div>
                        <div class="info-value"><?= $order['phone'] ?></div>
                    </div>
                    
                    <div class="info-group">
                        <div class="info-label">العنوان:</div>
                        <div class="info-value"><?= htmlspecialchars($order['address']) ?></div>
                    </div>
                    
                    <div class="info-group">
                        <div class="info-label">الولاية:</div>
                        <div class="info-value"><?= $order['wilaya_name'] ?? '--' ?></div>
                    </div>
                </div>
            </div>
            
            <h2 style="margin-bottom: 20px;">المنتجات المطلوبة</h2>
            
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>المنتج</th>
                            <th>السعر</th>
                            <th>الكمية</th>
                            <th>المجموع</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($items as $index => $item): ?>
                        <tr>
                            <td><?= $index + 1 ?></td>
                            <td>
                                <?= htmlspecialchars($item['product_name']) ?>
                                <?php if ($item['sku']): ?>
                                <div style="font-size: 12px; color: var(--gray);">SKU: <?= $item['sku'] ?></div>
                                <?php endif; ?>
                            </td>
                            <td><?= number_format($item['unit_price'], 2) ?> دج</td>
                            <td><?= $item['quantity'] ?></td>
                            <td><?= number_format($item['quantity'] * $item['unit_price'], 2) ?> دج</td>
                        </tr>
                        <?php endforeach; ?>
                        <tr class="total-row">
                            <td colspan="4" style="text-align: left;">المجموع الكلي</td>
                            <td><?= number_format($order_total, 2) ?> دج</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div class="action-buttons">
                <?php if ($order['status_id'] == 1): ?>
                <form action="orders.php" method="post" style="display: inline;">
                    <input type="hidden" name="order_id" value="<?= $order_id ?>">
                    <button type="submit" name="mark_as_sent" class="btn btn-primary">
                        <i class="fas fa-paper-plane"></i> تم الإرسال
                    </button>
                </form>
                <?php endif; ?>
                
                <a href="print_order.php?id=<?= $order_id ?>" target="_blank" class="btn btn-primary">
                    <i class="fas fa-print"></i> طباعة الفاتورة
                </a>
            </div>
        </div>
    </div>
</body>
</html>