<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/admin_auth.php';

header('Content-Type: application/json');

try {
    $account_number = trim($_POST['account_number'] ?? '');
    $type = strtolower(trim($_POST['type'] ?? ''));
    $amount = floatval($_POST['amount'] ?? 0);
    $status = strtolower(trim($_POST['status'] ?? 'successful'));
    $description = trim($_POST['description'] ?? '');
    $reference = trim($_POST['reference'] ?? '');
    $created_at = trim($_POST['created_at'] ?? '');

    if ($reference === '') {
        $reference = strtoupper(uniqid('TXN'));
    }

    if ($account_number === '' || $type === '' || $amount <= 0 || $created_at === '') {
        echo json_encode(['status' => 'error', 'message' => 'Please complete all required fields.']);
        exit;
    }

    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['status' => 'error', 'message' => 'Unauthorized — admin login required.']);
        exit;
    }

    // Get user
    $stmt = $pdo->prepare("SELECT id, account_balance FROM users WHERE account_number = ?");
    $stmt->execute([$account_number]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        echo json_encode(['status' => 'error', 'message' => 'User not found.']);
        exit;
    }

    $user_id = $user['id'];
    $old_balance = floatval($user['account_balance']);
    $new_balance = $old_balance;

    // Apply balance change if successful
    if ($status === 'successful') {
        if ($type === 'deposit') {
            $new_balance += $amount;
        } elseif (in_array($type, ['withdrawal', 'transfer'])) {
            if ($old_balance < $amount) {
                echo json_encode(['status' => 'error', 'message' => 'Insufficient balance.']);
                exit;
            }
            $new_balance -= $amount;
        }
    }

    // Insert transaction history with custom timestamp
    $insert = $pdo->prepare("INSERT INTO transactions 
        (user_id, account_number, reference, type, amount, description, status, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $insert->execute([$user_id, $account_number, $reference, $type, $amount, $description, $status, $created_at]);

    // Update balance if needed
    if ($status === 'successful') {
        $update = $pdo->prepare("UPDATE users SET account_balance = ? WHERE id = ?");
        $update->execute([$new_balance, $user_id]);
    }

    echo json_encode([
        'status' => 'success',
        'message' => 'History created successfully!',
        'reference' => $reference
    ]);

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Server error: ' . $e->getMessage()]);
}
