<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) session_start();

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Verify admin
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$txn_id = filter_var($_POST['transaction_id'] ?? 0, FILTER_VALIDATE_INT);
if (!$txn_id) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid transaction ID']);
    exit();
}

try {
    // Fetch the transaction
    $stmt = $pdo->prepare("
        SELECT t.*, u.username FROM transactions t
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.id = :id LIMIT 1
    ");
    $stmt->bindParam(':id', $txn_id, PDO::PARAM_INT);
    $stmt->execute();
    $txn = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$txn) {
        echo json_encode(['status' => '0', 'msg' => 'Transaction not found']);
        exit();
    }

    if ($txn['status'] !== 'pending') {
        echo json_encode(['status' => '0', 'msg' => 'Only pending transactions can be approved']);
        exit();
    }

    // Begin transaction
    $pdo->beginTransaction();

    // Mark transaction as successful
    $stmt = $pdo->prepare("
        UPDATE transactions
        SET status = 'successful', updated_at = NOW()
        WHERE id = :id
    ");
    $stmt->bindParam(':id', $txn_id, PDO::PARAM_INT);
    $stmt->execute();

    // If deposit type — credit user's main_balance
    $credited = false;
    if ($txn['transaction_type'] === 'deposit') {
        $stmt = $pdo->prepare("
            UPDATE users
            SET main_balance = main_balance + :amount, updated_at = NOW()
            WHERE id = :user_id
        ");
        $stmt->bindParam(':amount',  $txn['amount'],  PDO::PARAM_STR);
        $stmt->bindParam(':user_id', $txn['user_id'], PDO::PARAM_INT);
        $stmt->execute();
        $credited = true;
    }

    $pdo->commit();

    $msg = 'Transaction ' . $txn['transaction_ref'] . ' approved successfully.';
    if ($credited) {
        $msg .= ' ₦' . number_format($txn['amount'], 2) . ' has been credited to ' . $txn['username'] . '\'s main balance.';
    }

    echo json_encode(['status' => '1', 'msg' => $msg]);

} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
}
?>