<?php
/**
 * Verify Bank Reference (Admin/Accountant)
 * POST /api/v1/payments/verify-reference
 * 
 * User submits the bank reference number from their bank app.
 * We check if our Android bot has already received this reference.
 * If yes, auto-activate. If no, mark as pending_verification.
 */

declare(strict_types=1);

use App\Core\Database;
use App\Core\Security;
use App\Core\Validator;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();

if (!in_array($decoded['role'], ['admin', 'accountant', 'super_admin'])) {
    json_error('غير مصرح لك بتأكيد الدفع.', 403);
}

$data = Security::sanitize(input());
$paymentId = $data['payment_id'] ?? null;
$bankReference = trim($data['bank_reference'] ?? '');

$errors = Validator::validate($data, [
    'payment_id' => 'required',
    'bank_reference' => 'required'
]);

if ($errors || empty($bankReference)) {
    json_error('رقم المرجع البنكي مطلوب.', 422);
}

$db = Database::getInstance();
$tenantId = $decoded['tenant_id'];

try {
    // 1. Verify payment request exists and belongs to this tenant
    $stmt = $db->prepare("SELECT * FROM payment_requests WHERE id = ? AND tenant_id = ? AND status IN ('pending', 'uploaded')");
    $stmt->execute([$paymentId, $tenantId]);
    $payment = $stmt->fetch();

    if (!$payment) {
        json_error('طلب الدفع غير موجود أو تم معالجته بالفعل.', 404);
    }

    $db->beginTransaction();

    // 2. Check if the bot has already recorded this transaction
    $stmt = $db->prepare("SELECT * FROM bank_transactions WHERE bank_reference = ? AND is_claimed = 0 LIMIT 1");
    $stmt->execute([$bankReference]);
    $transaction = $stmt->fetch();

    if ($transaction) {
        // Match found! Check amount
        $expectedAmount = (float)$payment['amount_jod'];
        $receivedAmount = (float)$transaction['amount'];

        if (abs($expectedAmount - $receivedAmount) < 0.01) {
            // Amount matches exactly -> Auto Approve
            activateSubscription($db, $payment, $decoded['user_id']);

            $stmt = $db->prepare("UPDATE payment_requests SET status = 'approved', bank_reference = ?, verified_at = NOW() WHERE id = ?");
            $stmt->execute([$bankReference, $paymentId]);

            $stmt = $db->prepare("UPDATE bank_transactions SET is_claimed = 1 WHERE id = ?");
            $stmt->execute([$transaction['id']]);

            $db->commit();
            json_success([
                'status' => 'approved',
                'message' => 'تم التحقق من الدفع وتفعيل الاشتراك تلقائياً!'
            ], 'تم اعتماد الدفع وتفعيل الاشتراك');
        } else {
            // Amount mismatch -> Needs manual review
            $stmt = $db->prepare("UPDATE payment_requests SET status = 'uploaded', bank_reference = ?, admin_notes = 'المبلغ غير متطابق' WHERE id = ?");
            $stmt->execute([$bankReference, $paymentId]);
            $db->commit();
            
            json_success([
                'status' => 'uploaded',
                'message' => 'تم العثور على الحوالة ولكن المبلغ غير متطابق. تم تحويل الطلب للمراجعة الإدارية.'
            ], 'قيد المراجعة');
        }
    } else {
        // No matching transaction found yet. Wait for the bot.
        $stmt = $db->prepare("UPDATE payment_requests SET status = 'uploaded', bank_reference = ? WHERE id = ?");
        $stmt->execute([$bankReference, $paymentId]);
        $db->commit();

        json_success([
            'status' => 'uploaded',
            'message' => 'تم حفظ رقم المرجع بنجاح. سيتم تفعيل الاشتراك تلقائياً فور وصول تأكيد الحوالة من البنك.'
        ], 'تم حفظ المرجع (بانتظار التأكيد)');
    }

} catch (\Throwable $e) {
    if ($db->inTransaction()) $db->rollBack();
    error_log("Verify Reference Error: " . $e->getMessage());
    json_error('حدث خطأ أثناء معالجة رقم المرجع.', 500);
}

/**
 * Auto-activate subscription upon verified payment
 */
function activateSubscription(\PDO $db, array $payment, string $userId): void
{
    $stmt = $db->prepare("SELECT * FROM subscription_plans WHERE id = ? AND is_active = 1");
    $stmt->execute([$payment['plan_id']]);
    $plan = $stmt->fetch();

    if (!$plan) return;

    $startDate = date('Y-m-d H:i:s');
    $endDate   = date('Y-m-d H:i:s', strtotime('+30 days'));

    $stmt = $db->prepare("
        INSERT INTO subscriptions (tenant_id, plan_id, max_companies, max_invoices_per_month, max_users, price_jod, status, current_period_start, current_period_end, updated_at)
        VALUES (:t_id, :p_id, :max_c, :max_i, :max_u, :price, 'active', :start, :end, NOW())
        ON DUPLICATE KEY UPDATE
            plan_id = VALUES(plan_id),
            max_companies = VALUES(max_companies),
            max_invoices_per_month = VALUES(max_invoices_per_month),
            max_users = VALUES(max_users),
            price_jod = VALUES(price_jod),
            status = 'active',
            current_period_start = VALUES(current_period_start),
            current_period_end = VALUES(current_period_end),
            updated_at = NOW()
    ");

    $stmt->execute([
        't_id'  => $payment['tenant_id'],
        'p_id'  => $plan['id'],
        'max_c' => $plan['max_companies'],
        'max_i' => $plan['max_invoices_month'],
        'max_u' => $plan['max_users'],
        'price' => $plan['price_jod'],
        'start' => $startDate,
        'end'   => $endDate
    ]);

    // Log activation
    $logStmt = $db->prepare("INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, new_data) VALUES (?, ?, 'subscription.activated', 'payment', ?, ?)");
    $logStmt->execute([
        $payment['tenant_id'],
        $userId,
        $payment['id'],
        json_encode(['plan_id' => $plan['id'], 'auto_verified' => true])
    ]);
}
