<?php
// shamcash/finalize_deposit.php
// نظام الإيداع المتقدم (مع البونص وتسجيل الحركات المزدوجة)

// مسار ملف السجلات
define("LOG_FILE_FINALIZE", __DIR__ . "/deposit_errors.log");

if (!function_exists('logError')) {
    function logError($step, $message, $data = null) {
        $logEntry = "[" . date('Y-m-d H:i:s') . "] STEP {$step}: {$message}";
        if ($data !== null) { $logEntry .= " | Data: " . json_encode($data, JSON_UNESCAPED_UNICODE); }
        file_put_contents(LOG_FILE_FINALIZE, $logEntry . PHP_EOL, FILE_APPEND);
    }
}

if (!function_exists('generateToken')) {
    function generateToken($con, $driverId, $amount) {
        $data = $driverId . $amount . time() . 'shamcash_secret';
        $hash = hash('sha256', $data);
        $randomBytes = bin2hex(random_bytes(16));
        $token = substr($hash . $randomBytes, 0, 64);

        $stmt = $con->prepare("INSERT INTO payment_tokens (token, driverID, dateCreated, amount) VALUES (:token, :driverID, NOW(), :amount)");
        $stmt->execute([':token' => $token, ':driverID' => $driverId, ':amount' => $amount]);
        return $stmt->rowCount() > 0 ? $token : null;
    }
}

if (!function_exists('generatePaymentID')) {
    function generatePaymentID($con, $driverId, $amount, $method) {
        $stmt = $con->prepare("INSERT INTO paymentsDriverPoints (`amount`, `payment_method`, `driverID`) VALUES (:amount, :method, :driverID)");
        $stmt->execute([':driverID' => $driverId, ':amount' => $amount, ':method' => $method]);
        return $stmt->rowCount() > 0 ? $con->lastInsertId() : null;
    }
}

if (!function_exists('finalizeShamCashDeposit')) {
    function finalizeShamCashDeposit(PDO $con, $invoice_id) {
        
        // 1. جلب بيانات الفاتورة
        $stmt = $con->prepare("SELECT * FROM invoices_shamcash WHERE id = :id AND status = 'processing' LIMIT 1");
        $stmt->execute([':id' => $invoice_id]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$invoice) {
            logError("INIT", "Invoice not found or not processing", ['id' => $invoice_id]);
            return false;
        }

        // بدء معاملة لضمان سلامة البيانات
        $con->beginTransaction();

        try {
            $driverId = $invoice['driverID'];
            $originalAmount = (float)$invoice['amount'];
            $paymentMethod = 'shamcash';

            // 2. حساب المكافأة (Bonus Calculation) - نفس المنطق المرسل
            $bonusAmount = match ((int)$originalAmount) {
                100  => 100.0,
                200  => 210.0,
                400  => 450.0,
                1000 => 1100.0,
                default => $originalAmount,
            };

            // 3. إنشاء التوكنات
            $tokenDriver = generateToken($con, $driverId, $bonusAmount);
            if (!$tokenDriver) throw new Exception('Failed to generate driver token');

            $tokenSiro = generateToken($con, $driverId, $originalAmount);
            if (!$tokenSiro) throw new Exception('Failed to generate siro token');

            // 4. إنشاء Payment ID
            $paymentID = generatePaymentID($con, $driverId, $bonusAmount, $paymentMethod);
            if (!$paymentID) throw new Exception('Failed to generate payment ID');

            // 5. الإيداع في محفظة السائق (driverWallet) - المبلغ مع البونص
            $insertDriver = $con->prepare("INSERT INTO driverWallet (driverID, paymentID, amount, paymentMethod) VALUES (:driverID, :paymentID, :amount, :paymentMethod)");
            $insertDriver->execute([
                ':driverID' => $driverId,
                ':paymentID' => $paymentID,
                ':amount' => $bonusAmount,
                ':paymentMethod' => $paymentMethod
            ]);
            if ($insertDriver->rowCount() === 0) throw new Exception('Insert to driverWallet failed');
            
            // حرق توكن السائق
            $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token")->execute([':token' => $tokenDriver]);

            // 6. الإيداع في محفظة الشركة (siroWallet) - المبلغ الأصلي
            $insertSiro = $con->prepare("INSERT INTO siroWallet (driverId, passengerId, amount, paymentMethod, token, createdAt) VALUES (:driverId, :passengerId, :amount, :paymentMethod, :token, CURRENT_TIMESTAMP)");
            $insertSiro->execute([
                ':driverId' => $driverId,
                ':passengerId' => 'driver',
                ':amount' => $originalAmount,
                ':paymentMethod' => $paymentMethod,
                ':token' => $tokenSiro
            ]);
            if ($insertSiro->rowCount() === 0) throw new Exception('Insert to siroWallet failed');

            // حرق توكن الشركة
            $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token")->execute([':token' => $tokenSiro]);

            // 7. تحديث حالة الفاتورة إلى مكتملة
            $con->prepare("UPDATE invoices_shamcash SET status = 'completed', paid_at = NOW() WHERE id = :id")->execute([':id' => $invoice_id]);

            // اعتماد المعاملة
            $con->commit();
            logError("SUCCESS", "Transaction finalized for Invoice #$invoice_id");
            return true;

        } catch (Throwable $e) {
            $con->rollBack();
            logError("EXCEPTION", $e->getMessage(), ['invoice_id' => $invoice_id]);
            return false;
        }
    }
}
?>