<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/db.php';

// ============================================================
// META CONVERSIONS API — Helper Functions
// ============================================================

function metaHash($value) {
    if (empty($value)) return null;
    return hash('sha256', strtolower(trim($value)));
}

function normalizePhone($phone) {
    $phone = preg_replace('/[^0-9]/', '', $phone);
    if (substr($phone, 0, 1) === '0') {
        $phone = '213'. substr($phone, 1);
    }
    return $phone;
}

function sendMetaPurchaseEvent($pixelId, $accessToken, $eventData) {
    $url = "https://graph.facebook.com/v19.0/{$pixelId}/events";
    $payload = json_encode(['data' => [$eventData]]);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer '. $accessToken,
        ],
        CURLOPT_TIMEOUT => 10,
    ]);
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    return ['response' => $response, 'error' => $error];
}

// ============================================================
// جلب إعدادات الـ Pixel من الداتابيز
// ============================================================
$pixelId = null;
$pixelEnabled = false;
try {
    $pixelRow = $pdo->query("SELECT meta_pixel_id, meta_pixel_enabled FROM stores WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
    if ($pixelRow && $pixelRow['meta_pixel_enabled'] &&!empty(trim($pixelRow['meta_pixel_id']))) {
        $pixelId = trim($pixelRow['meta_pixel_id']);
        $pixelEnabled = true;
    }
} catch (Exception $e) {
    // نكمل حتى لو فشل جلب الـ Pixel
}

// ============================================================
// Access Token — حطه في ملف.env أفضل
// ============================================================
$accessToken = 'EAASUely9KJUBRAtjjLFmEEwQnZBs95gixfQnDNrYXENWnWIuwu424Wd62lJlqi4NurAiwRazxKwbLtOAjFmEwpPexLjbgJpeEZC1SlHksWJD0nNXZAJPWqETskT1PIKERAuYPIo4lDZCcFAyy7zrouZCgNOnmZAEnSCWEkxSAIZCaDZB4H00tjb5NnRlUPNlgRCbwZDZD';

// ============================================================
// معالجة الـ POST
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $customer_name = trim($_POST['customer_name']?? '');
    $phone = trim($_POST['phone']?? '');
    $phone2 = trim($_POST['phone2']?? '');
    $address = trim($_POST['address']?? '');
    $wilaya_id = $_POST['wilaya_id']?? '';
    $commune_id = isset($_POST['commune_id']) &&!empty($_POST['commune_id'])? (int)$_POST['commune_id'] : null;
    $delivery_type = $_POST['delivery_type']?? 'home';
    $quantity = max(1, (int)($_POST['quantity']?? 1));
    $product_id = (int)($_POST['product_id']?? 0);
    $variant_id = (int)($_POST['variant_id']?? 0);
    $delivery_company_id = (int)($_POST['delivery_company_id']?? 0);
    $selected_attributes = $_POST['selected_attributes']?? '';

    // التحقق من الحقول الإلزامية
    if (empty($customer_name) || empty($phone) || empty($wilaya_id) || empty($product_id)) {
        die("جميع الحقول المطلوبة يجب ملؤها");
    }
    if (!preg_match('/^\d+$/', $phone)) {
        die("رقم الهاتف الأساسي يجب أن يحتوي على أرقام فقط");
    }
    if (!empty($phone2) &&!preg_match('/^\d+$/', $phone2)) {
        die("رقم الهاتف الإضافي يجب أن يحتوي على أرقام فقط");
    }

    // جلب اسم الولاية عشان المطابقة المتقدمة
    $stmt = $pdo->prepare("SELECT name FROM wilayas WHERE id =?");
    $stmt->execute([$wilaya_id]);
    $wilaya_name = $stmt->fetchColumn()?: '';

    // جلب سعر المنتج / المتغير
    $unit_price = 0;
    $product_name_for_pixel = '';
    $product_sku = '';

    if ($variant_id) {
        $stmt = $pdo->prepare("SELECT pv.price, pv.stock, pv.sku, p.name FROM product_variants pv JOIN products p ON pv.product_id = p.id WHERE pv.id =?");
        $stmt->execute([$variant_id]);
        $variant = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$variant) die("المتغير غير موجود");
        if ($variant['stock'] < $quantity) die("المنتج غير متوفر أو الكمية المطلوبة غير متوفرة");
        $unit_price = $variant['price'];
        $product_name_for_pixel = $variant['name'];
        $product_sku = $variant['sku']?? '';
    } else {
        $stmt = $pdo->prepare("SELECT price, discounted_price, stock_quantity, name, sku FROM products WHERE id =?");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$product) die("المنتج غير موجود");
        if ($product['stock_quantity'] < $quantity) die("المنتج غير متوفر أو الكمية المطلوبة غير متوفرة");
        $unit_price = $product['discounted_price']?? $product['price'];
        $product_name_for_pixel = $product['name'];
        $product_sku = $product['sku']?? '';
    }

    // جلب سعر التوصيل
    $delivery_price_id = null;
    $delivery_price_value = 0;
    if ($delivery_company_id && $wilaya_id) {
        $stmt = $pdo->prepare("SELECT id, price FROM delivery_prices WHERE delivery_company_id =? AND wilaya_id =? AND delivery_type =?");
        $stmt->execute([$delivery_company_id, $wilaya_id, $delivery_type]);
        $delivery_price = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($delivery_price) {
            $delivery_price_id = $delivery_price['id'];
            $delivery_price_value = $delivery_price['price'];
        }
    }

    // المجموع الكلي
    $total_value = ($unit_price * $quantity) + $delivery_price_value;

    // ============================================================
    // حفظ الطلب في الداتابيز
    // ============================================================
    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare("
            INSERT INTO orders (
                customer_name, phone, phone2, address,
                order_date, status_id,
                delivery_company_id, delivery_price_id,
                wilaya_id, commune_id, delivery_type
            ) VALUES (?,?,?,?, NOW(), 1,?,?,?,?,?)
        ");
        $stmt->execute([
            $customer_name,
            $phone,
           !empty($phone2)? $phone2 : null,
            $address,
            $delivery_company_id,
            $delivery_price_id,
            $wilaya_id,
            $commune_id,
            $delivery_type,
        ]);
        $order_id = $pdo->lastInsertId();

        $stmt = $pdo->prepare("
            INSERT INTO order_items (
                order_id, product_variant_id, quantity,
                unit_price, selected_attribute_value
            ) VALUES (?,?,?,?,?)
        ");
        $stmt->execute([
            $order_id,
            $variant_id?: null,
            $quantity,
            $unit_price,
            $selected_attributes,
        ]);

        // تحديث المخزون
        if ($variant_id) {
            $stmt = $pdo->prepare("UPDATE product_variants SET stock = stock -? WHERE id =?");
            $stmt->execute([$quantity, $variant_id]);
        } else {
            $stmt = $pdo->prepare("UPDATE products SET stock_quantity = stock_quantity -? WHERE id =?");
            $stmt->execute([$quantity, $product_id]);
        }

        $pdo->commit();

        // إنشاء event_id فريد للـ Deduplication
        $event_id = 'purchase_'. $product_id. '_'. $order_id. '_'. time();

        // ============================================================
        // نحفظ بيانات العميل في السيشن عشان نرسلها للبكسل في صفحة التأكيد
        // ============================================================
        $_SESSION['customer_phone'] = $phone;
        $_SESSION['customer_name'] = $customer_name;
        $_SESSION['wilaya_name'] = $wilaya_name;
        $_SESSION['meta_event_id'] = $event_id;
        $_SESSION['meta_value'] = round((float)$total_value, 2);
        $_SESSION['meta_product_id'] = $product_id;
        $_SESSION['meta_product_name'] = $product_name_for_pixel;

    } catch (Exception $e) {
        $pdo->rollBack();
        die("حدث خطأ في حفظ الطلب: ". $e->getMessage());
    }

    // ============================================================
    // META CONVERSIONS API — إرسال حدث Purchase من السيرفر
    // ============================================================
    if ($pixelEnabled &&!empty($accessToken)) {

        $hashed_phone = metaHash(normalizePhone($phone));
        $hashed_name = metaHash($customer_name);

        $userData = [
            'ph' => $hashed_phone,
            'fn' => $hashed_name,
            'st' => metaHash($wilaya_name),
            'country' => metaHash('dz'),
            'client_ip_address' => $_SERVER['REMOTE_ADDR']?? null,
            'client_user_agent' => $_SERVER['HTTP_USER_AGENT']?? null,
            'fbp' =>!empty($_POST['fbp'])? $_POST['fbp'] : ($_COOKIE['_fbp']?? null),
            'fbc' =>!empty($_POST['fbc'])? $_POST['fbc'] : ($_COOKIE['_fbc']?? null)
        ];
        $userData = array_filter($userData, fn($v) =>!is_null($v) && $v!== '');

        $customData = [
            'value' => round((float)$total_value, 2),
            'currency' => 'DZD',
            'content_ids' => [(string)$product_id],
            'content_name' => $product_name_for_pixel,
            'content_type' => 'product',
            'num_items' => $quantity,
            'order_id' => (string)$order_id,
            'status' => 'completed',
            'contents' => [[
                'id' => (string)$product_id,
                'quantity' => $quantity,
                'item_price' => round((float)$unit_price, 2),
                'title' => $product_name_for_pixel,
                'sku' => $product_sku,
            ]],
        ];

        $eventData = [
            'event_name' => 'Purchase',
            'event_time' => time(),
            'event_id' => $event_id,
            'event_source_url' => (isset($_SERVER['HTTPS'])? 'https' : 'http')
                                 . '://'. ($_SERVER['HTTP_HOST']?? '')
                                 . '/submit_order.php',
            'action_source' => 'website',
            'user_data' => $userData,
            'custom_data' => $customData,
        ];

        $apiResult = sendMetaPurchaseEvent($pixelId, $accessToken, $eventData);

        $logMsg = date("Y-m-d H:i:s"). " | order_id=". $order_id
                . " | event_id=". $event_id
                . " | response=". $apiResult["response"]
                . " | curl_error=". $apiResult["error"]. "\n";
        file_put_contents(__DIR__. "/meta_api.log", $logMsg, FILE_APPEND);
    }

    header("Location: order_confirmation.php?order_id=$order_id");
    exit;

} else {
    header("Location: index.php");
    exit;
}
?>