"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]); ?>