<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';
require_once __DIR__ . '/../../includes/audit.php';

apply_cors();
$admin = require_admin();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

// GET   /transactions.php                 -> list (filter by status/gateway, paginate)
// GET   /transactions.php?id=5            -> single detail
// PATCH /transactions.php?id=5&action=status -> { status: VERIFIED|REJECTED } - approves UTR, extends user's plan

if ($method === 'GET' && isset($_GET['id'])) {
    $stmt = $pdo->prepare('SELECT * FROM payment_transactions WHERE id = :id');
    $stmt->execute([':id' => (int) $_GET['id']]);
    $row = $stmt->fetch();
    if (!$row) send_error('Transaction not found.', 404);
    send_success(['transaction' => $row]);
}

if ($method === 'GET') {
    [$page, $perPage, $offset] = paginate_params();
    $status = clean_str($_GET['status'] ?? '');
    $gateway = clean_str($_GET['gateway'] ?? '');

    $where = ['1=1'];
    $params = [];
    if ($status !== '') { $where[] = 'status = :status'; $params[':status'] = $status; }
    if ($gateway !== '') { $where[] = 'gateway = :gateway'; $params[':gateway'] = $gateway; }
    $whereSql = implode(' AND ', $where);

    $count = $pdo->prepare("SELECT COUNT(*) FROM payment_transactions WHERE $whereSql");
    $count->execute($params);
    $total = (int) $count->fetchColumn();

    $stmt = $pdo->prepare(
        "SELECT * FROM payment_transactions WHERE $whereSql ORDER BY created_at DESC LIMIT :limit OFFSET :offset"
    );
    foreach ($params as $k => $v) $stmt->bindValue($k, $v);
    $stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    send_success([
        'transactions' => $stmt->fetchAll(),
        'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
    ]);
}

if ($method === 'PATCH' && isset($_GET['id']) && $action === 'status') {
    $id = (int) $_GET['id'];
    $input = get_json_input();
    require_fields($input, ['status']);
    $newStatus = strtoupper(clean_str($input['status']));

    if (!in_array($newStatus, ['VERIFIED', 'REJECTED', 'SUCCESS', 'FAILED'], true)) {
        send_error('Invalid status value.', 422);
    }

    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare('SELECT * FROM payment_transactions WHERE id = :id FOR UPDATE');
        $stmt->execute([':id' => $id]);
        $txn = $stmt->fetch();

        if (!$txn) {
            $pdo->rollBack();
            send_error('Transaction not found.', 404);
        }

        // Idempotency guard: only activate once, regardless of repeated admin clicks
        $alreadyFinal = in_array($txn['status'], ['VERIFIED', 'SUCCESS', 'REJECTED', 'FAILED'], true);

        $upd = $pdo->prepare(
            'UPDATE payment_transactions SET status = :status, verified_by_admin = :admin, verified_at = NOW()
             WHERE id = :id'
        );
        $upd->execute([':status' => $newStatus, ':admin' => $admin['email'], ':id' => $id]);

        if (!$alreadyFinal && in_array($newStatus, ['VERIFIED', 'SUCCESS'], true)) {
            $extend = $pdo->prepare(
                'UPDATE users SET validity_days = validity_days + :days, activated_at = NOW()
                 WHERE email = :email'
            );
            $extend->execute([':days' => (int) $txn['validity_days_added'], ':email' => $txn['user_email']]);
        }

        $pdo->commit();
    } catch (Throwable $e) {
        $pdo->rollBack();
        send_error('Failed to update transaction: ' . $e->getMessage(), 500);
    }

    log_admin_action($admin['email'], 'UPDATE_TRANSACTION_STATUS', 'txn_id:' . $id, 'status=' . $newStatus);
    send_success(null, 'Transaction ' . strtolower($newStatus) . '.' . ($newStatus === 'VERIFIED' || $newStatus === 'SUCCESS' ? ' User plan extended.' : ''));
}

send_error('Invalid request.', 400);
