<?php
/**
 * Review Payment Request (Super Admin only)
 * POST /api/v1/payments/review
 * 
 * Manually approve or reject a payment request.
 */

declare(strict_types=1);

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

$decoded = AuthMiddleware::check();

if ($decoded['role'] !== 'super_admin') {
    json_error('هذه العملية لمدير النظام فقط.', 403);
}

$data = Security::sanitize(input());
$paymentId = $data['payment_id'] ?? null;
$action    = $data['action'] ?? null; // 'approve' or 'reject'
$notes     = $data['notes'] ?? '';

if (!$paymentId || !in_array($action, ['approve', 'reject'])) {
    json_error('معرف الطلب ونوع الإجراء (approve/reject) مطلوبان.', 422);
}

$db = Database::getInstance();

try {
    $stmt = $db->prepare("SELECT * FROM payment_requests WHERE id = ? AND status IN ('pending','uploaded','verified')");
    $stmt->execute([$paymentId]);
    $payment = $stmt->fetch();

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

    $db->beginTransaction();

    if ($action === 'approve') {
        // Activate subscription
        $stmt = $db->prepare("SELECT * FROM subscription_plans WHERE id = ? AND is_active = 1");
        $stmt->execute([$payment['plan_id']]);
        $plan = $stmt->fetch();

        if ($plan) {
            $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
            ]);
        }

        $stmt = $db->prepare("UPDATE payment_requests SET status = 'approved', admin_notes = ?, verified_at = NOW(), updated_at = NOW() WHERE id = ?");
        $stmt->execute([$notes, $paymentId]);
    } else {
        $stmt = $db->prepare("UPDATE payment_requests SET status = 'rejected', admin_notes = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$notes, $paymentId]);
    }

    // Audit log
    $logStmt = $db->prepare("INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, new_data) VALUES (?, ?, ?, 'payment', ?, ?)");
    $logStmt->execute([
        $payment['tenant_id'],
        $decoded['user_id'],
        "payment.{$action}d",
        $paymentId,
        json_encode(['notes' => $notes, 'reviewer' => $decoded['user_id']])
    ]);

    $db->commit();

    json_success([
        'payment_id' => $paymentId,
        'new_status'  => $action === 'approve' ? 'approved' : 'rejected'
    ], $action === 'approve' ? 'تم اعتماد الدفع وتفعيل الاشتراك' : 'تم رفض طلب الدفع');

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