<?php
session_start();


require_once __DIR__ . '/db.php';

// جلب إعدادات الـ Pixel
try {
    $pixel = $pdo->query("SELECT meta_pixel_id, meta_pixel_enabled FROM stores WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $pixel = null;
}
$pixel_enabled = $pixel && $pixel['meta_pixel_enabled'] &&!empty(trim($pixel['meta_pixel_id']));
$pixel_id = $pixel_enabled? htmlspecialchars(trim($pixel['meta_pixel_id'])) : '';

// دالة تطبيع الهاتف للبكسل
function normalizePhoneForPixel($phone) {
    $phone = preg_replace('/[^0-9]/', '', $phone);
    if (substr($phone, 0, 1) === '0') {
        $phone = '213'. substr($phone, 1);
    }
    return $phone;
}

$order_id = $_GET['order_id']?? null;
if (!$order_id) die("معرف الطلب غير محدد");

function getCommuneName($pdo, $commune_id) {
    if (!$commune_id) return '--';
    $stmt = $pdo->prepare("SELECT commune_name_ascii FROM algeria_cities WHERE id =?");
    $stmt->execute([$commune_id]);
    return $stmt->fetchColumn()?: '--';
}

function getDeliveryPrice($pdo, $order_id, $wilaya_id, $delivery_type, $delivery_company_id) {
    if (!$wilaya_id) return 0;
    $stmt = $pdo->prepare("SELECT price FROM delivery_prices WHERE wilaya_id =? AND delivery_type =? AND delivery_company_id =? LIMIT 1");
    $stmt->execute([$wilaya_id, $delivery_type, $delivery_company_id]);
    $price = $stmt->fetchColumn();
    return $price? floatval($price) : 0;
}

function formatSelectedAttributes($selected_attribute_value) {
    if (empty($selected_attribute_value) || $selected_attribute_value == '[]') return '<span style="color:#999;">بدون خصائص</span>';
    $attrs = json_decode($selected_attribute_value, true);
    if (json_last_error()!== JSON_ERROR_NONE) return '<span style="color:#999;">'.htmlspecialchars($selected_attribute_value).'</span>';
    if (empty($attrs)) return '<span style="color:#999;">بدون خصائص</span>';
    $html = '<div style="display:flex;flex-wrap:wrap;gap:5px;">';
    foreach ($attrs as $key => $value) {
        $bg = $key=='اللون'? '#ffebee' : ($key=='المقاس'||$key=='حجم'? '#e8f5e8' : '#e3f2fd');
        $html.= '<span style="background:'.$bg.';padding:3px 8px;border-radius:4px;font-size:12px;border:1px solid #ddd;"><strong>'.htmlspecialchars($key).':</strong> '.htmlspecialchars($value).'</span>';
    }
    return $html.'</div>';
}

try {
    $stmt = $pdo->prepare("SELECT o.*, w.name AS wilaya_name, dc.name AS delivery_company_name FROM orders o LEFT JOIN wilayas w ON o.wilaya_id = w.id LEFT JOIN delivery_companies dc ON o.delivery_company_id = dc.id WHERE o.id =?");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$order) die("الطلب غير موجود");

    $commune_name = getCommuneName($pdo, $order['commune_id']);
    $delivery_price = getDeliveryPrice($pdo, $order_id, $order['wilaya_id'], $order['delivery_type'], $order['delivery_company_id']);

    $stmt = $pdo->prepare("SELECT oi.*, pv.sku, p.name AS product_name, p.id as product_id 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 =?");
    $stmt->execute([$order_id]);
    $order_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $subtotal = 0;
    foreach ($order_items as $item) $subtotal += $item['unit_price'] * $item['quantity'];
    $total = $subtotal + $delivery_price;

} catch (PDOException $e) {
    die("Error: ". $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تأكيد الطلب - متجرنا</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@300;400;500;700;800&display=swap" rel="stylesheet">

    <?php if ($pixel_enabled && isset($_SESSION['customer_phone'])):?>
    <!--

    META PIXEL - صفحة التأكيد مع Advanced Matching

    ✅ نرسل بيانات العميل هنا عشان نحل تحذير "Set up manual advanced matching"
    ✅ البكسل يشفر البيانات تلقائيا بـ SHA-256
    ❌ ممنوع إضافة حدث Purchase هنا - يتم إرساله من submit_order.php فقط

    -->
    <script>
   !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');

    // نمرر بيانات العميل للبكسل - هذا يحل مشكلة Advanced Matching
    fbq('init', '<?php echo $pixel_id;?>', {
      ph: '<?php echo normalizePhoneForPixel($_SESSION['customer_phone']?? '');?>',
      fn: '<?php echo strtolower(trim($_SESSION['customer_name']?? ''));?>',
      st: '<?php echo strtolower(trim($_SESSION['wilaya_name']?? ''));?>',
      country: 'dz'
    });

    fbq('track', 'PageView');

    // ممنوع نرسل Purchase هنا - نرسله من السيرفر فقط
    </script>
    <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=<?php echo $pixel_id;?>&ev=PageView&noscript=1"/></noscript>

    <?php
    // نمسح السيشن بعد الاستخدام
    unset($_SESSION['customer_phone']);
    unset($_SESSION['customer_name']);
    unset($_SESSION['wilaya_name']);
    unset($_SESSION['meta_event_id']);
    unset($_SESSION['meta_value']);
    unset($_SESSION['meta_product_id']);
    unset($_SESSION['meta_product_name']);
   ?>
    <?php endif;?>

    <style>
        * { margin:0; padding:0; box-sizing:border-box; font-family:'Tajawal',sans-serif; }
        body { background:linear-gradient(135deg,#667eea 0%,#764ba2 100%); min-height:100vh; padding:40px 20px; }
       .container { max-width:900px; margin:0 auto; }
       .success-card { background:white; border-radius:20px; overflow:hidden; box-shadow:0 20px 60px rgba(0,0,0,0.3); animation:slideIn 0.5s ease-out; }
        @keyframes slideIn { from{opacity:0;transform:translateY(-30px)} to{opacity:1;transform:translateY(0)} }
       .success-header { background:linear-gradient(135deg,#4CAF50,#45a049); color:white; padding:40px 30px; text-align:center; }
       .success-header i { font-size:80px; margin-bottom:20px; animation:bounce 1s infinite; }
        @keyframes bounce { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-10px)} }
       .success-header h1 { font-size:36px; margin-bottom:10px; font-weight:800; }
       .success-header p { font-size:18px; opacity:0.9; }
       .order-number { background:rgba(255,255,255,0.2); display:inline-block; padding:10px 30px; border-radius:50px; margin-top:20px; font-size:20px; font-weight:700; }
       .order-content { padding:40px; }
       .info-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(250px,1fr)); gap:20px; margin-bottom:30px; background:#f8f9fa; padding:25px; border-radius:15px; }
       .info-item { display:flex; align-items:center; gap:15px; }
       .info-icon { width:50px; height:50px; background:linear-gradient(135deg,#667eea,#764ba2); border-radius:50%; display:flex; align-items:center; justify-content:center; color:white; font-size:20px; }
       .info-details { flex:1; }
       .info-label { font-size:14px; color:#666; margin-bottom:5px; }
       .info-value { font-size:18px; font-weight:700; color:#333; }
       .delivery-type-badge { display:inline-block; padding:4px 12px; border-radius:20px; font-size:14px; font-weight:600; }
       .delivery-home { background:#e3f2fd; color:#1976d2; }
       .delivery-office { background:#f3e5f5; color:#7b1fa2; }
       .products-section { margin:30px 0; }
       .section-title { font-size:22px; color:#333; margin-bottom:20px; display:flex; align-items:center; gap:10px; }
       .section-title i { color:#667eea; }
       .products-table { width:100%; border-collapse:collapse; background:white; border-radius:15px; overflow:hidden; box-shadow:0 5px 15px rgba(0,0,0,0.05); }
       .products-table th { background:linear-gradient(135deg,#667eea,#764ba2); color:white; font-weight:600; padding:15px; text-align:right; }
       .products-table td { padding:15px; border-bottom:1px solid #eee; }
       .products-table tr:last-child td { border-bottom:none; }
       .products-table tr:hover { background:#f8f9fa; }
       .price-summary { background:linear-gradient(135deg,#f8f9fa,#e9ecef); padding:25px; border-radius:15px; margin-top:30px; }
       .summary-row { display:flex; justify-content:space-between; padding:12px 0; border-bottom:1px dashed #ddd; font-size:16px; }
       .summary-row:last-child { border-bottom:none; }
       .summary-row.total { font-size:24px; font-weight:800; color:#4CAF50; padding-top:15px; margin-top:10px; border-top:2px solid #4CAF50; }
       .delivery-free { background:#d4edda; color:#155724; padding:5px 15px; border-radius:20px; font-weight:600; font-size:14px; }
       .action-buttons { display:flex; gap:15px; justify-content:center; margin-top:30px; }
       .btn { padding:15px 30px; border-radius:50px; text-decoration:none; font-weight:700; transition:all 0.3s ease; display:inline-flex; align-items:center; gap:10px; border:none; cursor:pointer; }
       .btn-primary { background:linear-gradient(135deg,#667eea,#764ba2); color:white; box-shadow:0 5px 15px rgba(102,126,234,0.4); }
       .btn-primary:hover { transform:translateY(-3px); box-shadow:0 8px 25px rgba(102,126,234,0.5); }
       .btn-secondary { background:white; color:#667eea; border:2px solid #667eea; }
       .btn-secondary:hover { background:#667eea; color:white; }
        @media(max-width:768px) {
           .success-header h1 { font-size:28px; }
           .order-content { padding:20px; }
           .info-grid { grid-template-columns:1fr; }
           .products-table { font-size:14px; }
           .products-table th,.products-table td { padding:10px; }
           .action-buttons { flex-direction:column; }
           .btn { width:100%; justify-content:center; }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="success-card">
        <div class="success-header">
            <i class="fas fa-check-circle"></i>
            <h1>تم تسجيل طلبك بنجاح!</h1>
            <p>شكراً لتسوقك معنا. سنتواصل معك قريباً لتأكيد الطلب</p>
            <div class="order-number">
                <i class="fas fa-hashtag"></i> رقم الطلب: <?php echo str_pad($order['id'], 5, '0', STR_PAD_LEFT);?>
            </div>
        </div>

        <div class="order-content">
            <div class="info-grid">
                <div class="info-item">
                    <div class="info-icon"><i class="fas fa-user"></i></div>
                    <div class="info-details">
                        <div class="info-label">الاسم</div>
                        <div class="info-value"><?php echo htmlspecialchars($order['customer_name']);?></div>
                    </div>
                <div class="info-item">
                    <div class="info-icon"><i class="fas fa-phone"></i></div>
                    <div class="info-details">
                        <div class="info-label">رقم الهاتف</div>
                        <div class="info-value" dir="ltr"><?php echo htmlspecialchars($order['phone']);?></div>
                        <?php if (!empty($order['phone2'])):?>
                            <div style="font-size:14px;color:#666;margin-top:5px;" dir="ltr"><i class="fas fa-phone-alt"></i> <?php echo htmlspecialchars($order['phone2']);?></div>
                        <?php endif;?>
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-icon"><i class="fas fa-map-marker-alt"></i></div>
                    <div class="info-details">
                        <div class="info-label">الولاية</div>
                        <div class="info-value"><?php echo htmlspecialchars($order['wilaya_name']);?></div>
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-icon"><i class="fas fa-city"></i></div>
                    <div class="info-details">
                        <div class="info-label">البلدية</div>
                        <div class="info-value"><?php echo htmlspecialchars($commune_name);?></div>
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-icon"><i class="fas fa-truck"></i></div>
                    <div class="info-details">
                        <div class="info-label">نوع التوصيل</div>
                        <div class="info-value">
                            <span class="delivery-type-badge <?php echo $order['delivery_type']==='home'?'delivery-home':'delivery-office';?>">
                                <i class="fas fa-<?php echo $order['delivery_type']==='home'?'home':'building';?>"></i>
                                <?php echo $order['delivery_type']==='home'?'توصيل إلى المنزل':'توصيل إلى المكتب';?>
                            </span>
                        </div>
                    </div>
                <div class="info-item">
                    <div class="info-icon"><i class="fas fa-box"></i></div>
                    <div class="info-details">
                        <div class="info-label">شركة التوصيل</div>
                        <div class="info-value"><?php echo htmlspecialchars($order['delivery_company_name']);?></div>
                    </div>
                </div>
            </div>

            <?php if (!empty($order['address'])):?>
            <div style="background:#fff3e0;padding:15px;border-radius:10px;margin-bottom:30px;border-right:4px solid #ff9800;">
                <i class="fas fa-map-pin" style="color:#ff9800;margin-left:10px;"></i>
                <strong>العنوان بالكامل:</strong> <?php echo htmlspecialchars($order['address']);?>
            </div>
            <?php endif;?>

            <div class="products-section">
                <h2 class="section-title"><i class="fas fa-shopping-bag"></i> منتجات الطلب</h2>
                <table class="products-table">
                    <thead>
                        <tr>
                            <th>المنتج</th>
                            <th>الخصائص</th>
                            <th>الكمية</th>
                            <th>السعر</th>
                            <th>الإجمالي</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($order_items as $item):
                            $item_total = $item['unit_price'] * $item['quantity'];
                       ?>
                        <tr>
                            <td style="font-weight:600;"><?php echo htmlspecialchars($item['product_name']);?></td>
                            <td><?php echo formatSelectedAttributes($item['selected_attribute_value']);?></td>
                            <td><?php echo $item['quantity'];?></td>
                            <td><?php echo number_format($item['unit_price'], 2);?> دج</td>
                            <td style="font-weight:600;color:#4CAF50;"><?php echo number_format($item_total, 2);?> دج</td>
                        </tr>
                        <?php endforeach;?>
                    </tbody>
                </table>
            </div>

            <div class="price-summary">
                <div class="summary-row">
                    <span>مجموع المنتجات:</span>
                    <span><strong><?php echo number_format($subtotal, 2);?></strong> دج</span>
                </div>
                <div class="summary-row">
                    <span>تكلفة التوصيل:</span>
                    <span>
                        <?php if ($delivery_price == 0):?>
                            <span class="delivery-free"><i class="fas fa-gift"></i> مجاني</span>
                        <?php else:?>
                            <strong><?php echo number_format($delivery_price, 2);?></strong> دج
                        <?php endif;?>
                    </span>
                </div>
                <div class="summary-row total">
                    <span>الإجمالي الكلي:</span>
                    <span><?php echo number_format($total, 2);?> دج</span>
                </div>
            </div>

            <div style="background:#e3f2fd;padding:20px;border-radius:10px;margin:30px 0;text-align:center;">
                <i class="fas fa-info-circle" style="color:#2196F3;font-size:24px;margin-bottom:10px;display:block;"></i>
                <p style="font-size:16px;color:#1976d2;margin:0;">
                    <strong>سيتم التواصل معك على الرقم <?php echo htmlspecialchars($order['phone']);?> لتأكيد الطلب وتحديد موعد التوصيل</strong>
                </p>
            </div>

            <div class="action-buttons">
                <a href="index.php" class="btn btn-primary"><i class="fas fa-home"></i> العودة للرئيسية</a>
                <a href="track_order.php" class="btn btn-secondary"><i class="fas fa-search"></i> تتبع طلباتي</a>
            </div>
        </div>
    </div>
</div>
</body>
</html>