<?php
/*************************************************
 * receive_transaction.php
 * نظام مالي - ملف استقبال العمليات (محمي)
 *************************************************/

/************** إعدادات الحماية **************/
define('SYSTEM_SECRET_KEY', 'A9x#91!FINANCE@2025');

/************** ملف تسجيل الأخطاء **************/
define('LOG_FILE', __DIR__ . '/finance_errors.log');

/************** دالة تسجيل الأخطاء **************/
function logError($message)
{
    file_put_contents(
        LOG_FILE,
        date('Y-m-d H:i:s') . ' | ' . $message . PHP_EOL,
        FILE_APPEND
    );
}

/************** اتصال قاعدة النظام المالي **************/
$host = "localhost";
$db   = "finance_system";
$user = "root";
$pass = "";

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$db;charset=utf8mb4",
        $user,
        $pass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    logError("DB Connection Failed");
    die("ERROR");
}

/************** السماح بـ POST فقط **************/
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    logError("Invalid Request Method");
    die("ERROR");
}

/************** استقبال البيانات **************/
$secret_key    = $_POST['secret_key']    ?? '';
$agent_id      = $_POST['agent_id']      ?? null;
$service_code  = $_POST['service_code']  ?? null;
$quantity      = (int)($_POST['quantity'] ?? 1);
$source_system = $_POST['source_system'] ?? null;
$source_ref_id = $_POST['source_ref_id'] ?? null;

/************** التحقق من التوكن **************/
if ($secret_key !== SYSTEM_SECRET_KEY) {
    logError("Invalid Secret Key");
    die("ERROR");
}

/************** تحقق أساسي **************/
if (
    !$agent_id ||
    !$service_code ||
    !$source_system ||
    !$source_ref_id ||
    $quantity <= 0
) {
    logError("Missing Data");
    die("ERROR");
}

/************** منع التكرار **************/
$stmt = $pdo->prepare("
    SELECT id
    FROM agent_transactions
    WHERE source_system = ?
      AND source_ref_id = ?
    LIMIT 1
");
$stmt->execute([$source_system, $source_ref_id]);

if ($stmt->fetch()) {
    logError("Duplicate Transaction Blocked");
    die("DUPLICATE");
}

/************** جلب الخدمة **************/
$stmt = $pdo->prepare("
    SELECT id 
    FROM services 
    WHERE code = ?
");
$stmt->execute([$service_code]);
$service = $stmt->fetch();

if (!$service) {
    logError("Service Not Found: $service_code");
    die("ERROR");
}

$service_id = $service['id'];

/************** جلب سعر المندوب **************/
$stmt = $pdo->prepare("
    SELECT price
    FROM agent_service_prices
    WHERE agent_id = ?
      AND service_id = ?
      AND active_to IS NULL
    ORDER BY active_from DESC
    LIMIT 1
");
$stmt->execute([$agent_id, $service_id]);
$price = $stmt->fetchColumn();

if ($price === false) {
    logError("Price Not Defined (Agent:$agent_id Service:$service_id)");
    die("ERROR");
}

/************** الحساب **************/
$unit_price   = (float)$price;
$total_amount = $unit_price * $quantity;

/************** إدخال العملية **************/
$stmt = $pdo->prepare("
    INSERT INTO agent_transactions
    (
        agent_id,
        service_id,
        source_system,
        source_ref_id,
        quantity,
        unit_price,
        total_amount,
        created_at
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
");

$stmt->execute([
    $agent_id,
    $service_id,
    $source_system,
    $source_ref_id,
    $quantity,
    $unit_price,
    $total_amount
]);

/************** نجاح **************/
echo "SUCCESS";
