

<?php
// shamcash/save_transactions.php
// يعتمد حصرياً على Note (Invoice Number)

ini_set('display_errors', 0); 
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

$log_file = __DIR__ . '/transactions.log';
$last_id_file = __DIR__ . '/last_id.txt';

function logMsg($msg) {
    global $log_file;
    $time = date('[H:i:s]');
    @file_put_contents($log_file, "$time $msg" . PHP_EOL, FILE_APPEND);
}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200); exit;
}

// --- 1. الاتصال بقاعدة البيانات ---
// البحث عن jwtconnect.php في المجلدات العلوية
$possible_paths = [__DIR__ . '/../jwtconnect.php', __DIR__ . '/../../jwtconnect.php'];
$db_connected = false;
foreach ($possible_paths as $path) {
    if (file_exists($path)) { include $path; if(isset($con)){ $db_connected = true; break; } }
}

if (!$db_connected) {
    logMsg("CRITICAL: DB Connection Failed.");
    echo json_encode(["status" => "error", "msg" => "DB Failed"]); exit;
}

// تضمين ملف الإيداع المالي
if (file_exists(__DIR__ . "/finalize_deposit.php")) {
    include __DIR__ . "/finalize_deposit.php";
} else {
    logMsg("CRITICAL: finalize_deposit.php missing"); exit;
}

// --- 2. استقبال البيانات ---
$raw = file_get_contents("php://input");
if (empty($raw)) { echo json_encode(["status" => "waiting"]); exit; }
$data = json_decode($raw, true);
if (!$data) { echo json_encode(["status" => "error"]); exit; }

if (!file_exists($last_id_file)) { @file_put_contents($last_id_file, "0"); }
$last_id = (int)@file_get_contents($last_id_file);

// --- 3. المعالجة ---
$processed = 0;
$txns = array_reverse($data);

foreach ($txns as $trx) {
    $tid = isset($trx['id']) ? (int)$trx['id'] : 0;
    
    if ($tid > $last_id) {
        $amt = (float)($trx['amount'] ?? 0);
        $note = $trx['note'] ?? '';
        $status_log = "IGNORED";

        // شرط الإيداع: مبلغ موجب + وجود ملاحظة رقمية
        // نستخرج الأرقام فقط من الملاحظة (رقم الفاتورة)
        $invoice_num = preg_replace('/[^0-9]/', '', $note);

        if ($amt > 0 && !empty($invoice_num) && strlen($invoice_num) >= 5) {
            
            // البحث المباشر عن الفاتورة برقمها والمبلغ
            $stmt = $con->prepare("SELECT id FROM invoices_shamcash WHERE invoice_number = :inv AND amount = :amt AND status = 'pending' LIMIT 1");
            $stmt->execute([':inv' => $invoice_num, ':amt' => $amt]);
            $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($invoice) {
                $inv_id = $invoice['id'];
                
                // حجز الفاتورة فوراً
                $upd = $con->prepare("UPDATE invoices_shamcash SET status = 'processing', transaction_id = :tid WHERE id = :id AND status = 'pending'");
                $upd->execute([':tid' => $tid, ':id' => $inv_id]);

                if ($upd->rowCount() > 0) {
                    // استدعاء الفاينلايز (مع البونص والتوكنات)
                    if (finalizeShamCashDeposit($con, $inv_id)) {
                        $status_log = "SUCCESS (Inv#$inv_id)";
                    } else {
                        $status_log = "FAILED_FINALIZE (Inv#$inv_id)";
                        // إعادة الحالة للفشل
                        $con->prepare("UPDATE invoices_shamcash SET status = 'failed' WHERE id = :id")->execute([':id' => $inv_id]);
                    }
                } else {
                    $status_log = "RACE_CONDITION";
                }
            } else {
                $status_log = "NO_MATCHING_INVOICE ($invoice_num)";
            }
        } elseif ($amt > 0) {
            $status_log = "INVALID_NOTE";
        }

        logMsg("ID:$tid | Note:$note | Amt:$amt | $status_log");
        $last_id = $tid;
        $processed++;
    }
}

if ($processed > 0) {
    @file_put_contents($last_id_file, $last_id);
}

echo json_encode(["status" => "success", "processed" => $processed]);
?>