<?php
include "../../jwtconnect.php";

// ------------------------------
// قراءة HMAC من الهيدر أو من الـ query
// ------------------------------
$received_hmac = $_SERVER['HTTP_HMAC'] ?? ($_GET['hmac'] ?? '');
$received_hmac = trim($received_hmac);

// ------------------------------
// قراءة البيانات القادمة من Paymob
// ------------------------------
$raw_body = file_get_contents("php://input");
$data = json_decode($raw_body, true);

// ------------------------------
// المفتاح السري
// ------------------------------
$secret_key = getenv('hmacPaymob');

// ------------------------------
// دالة لتحويل القيم إلى النصوص
// ------------------------------
function normalize($value) {
    if ($value === true) return 'true';
    if ($value === false) return 'false';
    if (is_null($value)) return '';
    return (string)$value;
}

// ------------------------------
// التحقق من صحة HMAC
// ------------------------------
function isValidHmac($data, $secret_key, $received_hmac) {
    if (!isset($data['obj'])) return false;

    $obj = $data['obj'];

    // دمج جميع الحقول بشكل متسلسل
    $fields = [
        normalize($obj['amount_cents'] ?? ''),
        normalize($obj['created_at'] ?? ''),
        normalize($obj['currency'] ?? ''),
        normalize($obj['error_occured'] ?? false),
        normalize($obj['has_parent_transaction'] ?? false),
        normalize($obj['id'] ?? ''),
        normalize($obj['integration_id'] ?? ''),
        normalize($obj['is_3d_secure'] ?? false),
        normalize($obj['is_auth'] ?? false),
        normalize($obj['is_capture'] ?? false),
        normalize($obj['is_refunded'] ?? false),
        normalize($obj['is_standalone_payment'] ?? false),
        normalize($obj['is_voided'] ?? false),
        normalize($obj['order']['id'] ?? ''),
        normalize($obj['owner'] ?? ''),
        normalize($obj['pending'] ?? false),
        normalize($obj['source_data']['pan'] ?? ''),
        normalize($obj['source_data']['sub_type'] ?? ''),
        normalize($obj['source_data']['type'] ?? ''),
        normalize($obj['success'] ?? false)
    ];

    // دمج الحقول في رسالة واحدة
    $message = implode('', $fields);

    // حساب HMAC باستخدام المفتاح السري
    $calculated_hmac = hash_hmac('sha512', $message, $secret_key);

    // طباعة الرسائل لأغراض التصحيح
    // error_log("🔐 Message used for HMAC: " . $message);
    // error_log("🔐 Calculated HMAC: " . $calculated_hmac);
    // error_log("📩 Received HMAC: " . $received_hmac);
    // error_log("Calculated HMAC length: " . strlen($calculated_hmac));
    // error_log("Received HMAC length: " . strlen($received_hmac));
    
    // التحقق من تطابق HMAC
    if (hash_equals($calculated_hmac, $received_hmac)) {
        error_log("✅ Valid HMAC signature verified.");
        return $calculated_hmac;
    } else {
        http_response_code(401);
        echo json_encode(["error" => "Unauthorized – Invalid HMAC"]);
        exit;
    }
}
isValidHmac($data, $secret_key, $received_hmac);
// ------------------------------
// إذا كانت HMAC صحيحة، نتابع العملية
// ------------------------------
if ($data && isset($data['obj'])) {
    $transaction = $data['obj'];

    $payment_id = $transaction['id'] ?? null;
    $amount = $transaction['amount_cents'] ?? 0;
    $status = $transaction['success'] ?? false;
    $is_voided = $transaction['is_voided'] ?? false;
    $is_refunded = $transaction['is_refunded'] ?? false;
    $order_id = $transaction['order']['id'] ?? null;
    $merchant_order_id = $transaction['order']['merchant_order_id'] ?? null;
    $payment_method = $transaction['source_data']['type'] ?? 'unknown';
    $card_last4 = $transaction['source_data']['pan'] ?? '****';
    $transaction_type = $transaction['data']['migs_transaction']['type'] ?? 'UNKNOWN';
    $created_at = $transaction['created_at'] ?? date("Y-m-d H:i:s");
    $user_id = $transaction['order']['shipping_data']['phone_number'];

    // التحقق من حالة الدفع
    if (!$status) {
        error_log("❌ Invalid payment status: " . $status);
        echo json_encode(["error" => "Invalid payment status"]);
        exit;
    }

    // إضافة البيانات إلى قاعدة البيانات
    $query = "INSERT INTO paymentsLog (`payment_id`, `user_id`, `amount`, `status`) 
              VALUES (:payment_id, :user_id, :amount, :status)";

    $stmt = $con->prepare($query);
    $stmt->bindParam(':payment_id', $payment_id);
    $stmt->bindParam(':user_id', $user_id);
    $stmt->bindParam(':amount', $amount);
    $stmt->bindParam(':status', $status);

    try {
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            http_response_code(200);
            echo json_encode(["success" => true, "message" => "Payment data saved successfully"]);
        } else {
            http_response_code(200);
            echo json_encode(["success" => false, "message" => "Payment data already up to date."]);
        }
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(["error" => "Failed to execute the query: " . $e->getMessage()]);
    }
}
?>