<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require '../../../db.php';

// Auth Check (Simple Token Check for now, ideally JWT)
$headers = getallheaders();
if (!isset($headers['Authorization'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}
// Assume Bearer Token contains UserID simply for this test environment
// In prod, verify JWT. Here we mock getUserIdFromToken
$token = str_replace('Bearer ', '', $headers['Authorization']);
// For test: Token is just the user ID? Or a static string?
// Let's assume for now we trust the client sends correct "user_id" in body for this Phase, 
// OR we query a sessions table.
// Given previous phases, we might not have full JWT middleware yet. 
// I will check `profile/me.php` logic later. For now, I'll rely on POST `sender_id`.
// SECURITY NOTE: This is weak. I should verify.

$data = json_decode(file_get_contents("php://input"));

if (!isset($data->sender_id) || !isset($data->recipient_id) || !isset($data->amount)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing data']);
    exit();
}

$sender_id = $data->sender_id;
$recipient_id = $data->recipient_id;
$amount = (int)$data->amount;
$type = isset($data->type) ? $data->type : 'send'; // 'send', 'gift'

if ($amount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid amount']);
    exit();
}

try {
    $pdo->beginTransaction();

    // Check Balance
    $stmt = $pdo->prepare("SELECT diamonds FROM i_users WHERE iuid = ?");
    $stmt->execute([$sender_id]);
    $sender = $stmt->fetch();

    if (!$sender || $sender['diamonds'] < $amount) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'Insufficient funds']);
        exit();
    }

    // Deduct
    $pdo->prepare("UPDATE i_users SET diamonds = diamonds - ? WHERE iuid = ?")->execute([$amount, $sender_id]);

    // Add
    $pdo->prepare("UPDATE i_users SET diamonds = diamonds + ? WHERE iuid = ?")->execute([$amount, $recipient_id]);

    // Log Transaction (Sender)
    $pdo->prepare("INSERT INTO wallet_transactions (user_id, type, amount, related_user_id, status) VALUES (?, ?, ?, ?, 'completed')")
        ->execute([$sender_id, $type, -$amount, $recipient_id]);

    // Log Transaction (Recipient)
    $pdo->prepare("INSERT INTO wallet_transactions (user_id, type, amount, related_user_id, status) VALUES (?, 'receive', ?, ?, 'completed')")
        ->execute([$recipient_id, $amount, $sender_id]);

    $pdo->commit();
    echo json_encode(['success' => true, 'message' => 'Transaction successful']);

} catch (Exception $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Transaction failed: ' . $e->getMessage()]);
}
?>
