<?php
require_once 'db.php';

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

$method = $_SERVER['REQUEST_METHOD'];
$pdo = db();

if ($method === 'GET') {
    $action = $_GET['action'] ?? 'list';

    if ($action === 'next_id') {
        // Get the last TT ID
        $stmt = $pdo->query("SELECT tt_id FROM tt_transactions ORDER BY id DESC LIMIT 1");
        $last = $stmt->fetchColumn();

        if ($last) {
            // Extract number part. Assuming format TT-XX
            if (preg_match('/TT-(\d+)/', $last, $matches)) {
                $num = intval($matches[1]);
                $nextNum = $num + 1;
                $nextId = 'TT-' . str_pad($nextNum, 2, '0', STR_PAD_LEFT);
            } else {
                // Fallback if format is weird
                $nextId = 'TT-01';
            }
        } else {
            $nextId = 'TT-01';
        }
        echo json_encode(['next_id' => $nextId]);
        exit;
    }

    if ($action === 'list') {
        // Join with agents to get agent name
        $stmt = $pdo->query("
            SELECT t.*, a.agent_name 
            FROM tt_transactions t
            LEFT JOIN agents a ON t.agent_id = a.id
            ORDER BY t.id DESC
        ");
        echo json_encode($stmt->fetchAll());
        exit;
    }
    if ($action === 'get') {
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        $stmt = $pdo->prepare("SELECT t.*, a.agent_name FROM tt_transactions t LEFT JOIN agents a ON t.agent_id=a.id WHERE t.id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        if (!$row) {
            http_response_code(404);
            echo json_encode(['error' => 'Not found']);
            exit;
        }
        echo json_encode($row);
        exit;
    }
} elseif ($method === 'POST') {
    $action = $_GET['action'] ?? 'create';
    $data = json_decode(file_get_contents('php://input'), true);
    if (!$data) $data = $_POST;

    $tt_id = $data['tt_id'] ?? '';
    $agent_id = $data['agent_id'] ?? '';
    $currency = $data['currency'] ?? '';
    $amount_pkr = $data['amount_pkr'] ?? 0;
    $currency_bought = $data['currency_bought'] ?? 0;
    $exchange_rate = $data['exchange_rate'] ?? 0;
    $details = $data['details'] ?? '';

    if (empty($tt_id) || empty($agent_id) || empty($currency)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        exit;
    }

    try {
        if ($action === 'create') {
            $stmt = $pdo->prepare("
                INSERT INTO tt_transactions 
                (tt_id, agent_id, currency, amount_pkr, currency_bought, exchange_rate, details)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$tt_id, $agent_id, $currency, $amount_pkr, $currency_bought, $exchange_rate, $details]);
            echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]);
            exit;
        }
        if ($action === 'update') {
            $id = isset($data['id']) ? (int)$data['id'] : 0;
            if (!$id) {
                http_response_code(400);
                echo json_encode(['error' => 'ID required']);
                exit;
            }
            $stmt = $pdo->prepare("
                UPDATE tt_transactions
                SET tt_id=?, agent_id=?, currency=?, amount_pkr=?, currency_bought=?, exchange_rate=?, details=?
                WHERE id=?
            ");
            $stmt->execute([$tt_id, $agent_id, $currency, $amount_pkr, $currency_bought, $exchange_rate, $details, $id]);
            echo json_encode(['success' => true]);
            exit;
        }
        if ($action === 'delete') {
            $id = isset($data['id']) ? (int)$data['id'] : 0;
            if (!$id) {
                http_response_code(400);
                echo json_encode(['error' => 'ID required']);
                exit;
            }
            $stmt = $pdo->prepare("DELETE FROM tt_transactions WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(['success' => true]);
            exit;
        }
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
        exit;
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
}
