<?php
ob_start(); 

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

header('Content-Type: application/json; charset=utf-8');

// 1. Seguridad
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Sesión expirada']);
    exit;
}

require_once __DIR__ . '/../core/api.php'; 

$user_id = $_SESSION['user_id'];
$amount = filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT);
$description = filter_var($_POST['description'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$date = $_POST['transaction_date'] ?? date('Y-m-d'); 

// Validación básica
if (!$amount || !$description) {
    echo json_encode(['success' => false, 'message' => 'Falta monto o descripción']);
    exit;
}

$receipt_path = null;

if (isset($_FILES['receipt']) && $_FILES['receipt']['error'] === UPLOAD_ERR_OK) {
    
    $meses = [
        1 => 'enero', 2 => 'febrero', 3 => 'marzo', 4 => 'abril', 
        5 => 'mayo', 6 => 'junio', 7 => 'julio', 8 => 'agosto', 
        9 => 'septiembre', 10 => 'octubre', 11 => 'noviembre', 12 => 'diciembre'
    ];
    $mesActual = $meses[(int)date('n')];
    
    $baseDir = '../uploads/finances/'; 
    $targetDir = $baseDir . $mesActual . '/';
    
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0755, true);
    }
    
    $ext = pathinfo($_FILES['receipt']['name'], PATHINFO_EXTENSION);
    $filename = 'mobile_' . uniqid() . '.' . $ext;
    $targetFile = $targetDir . $filename;
    
    if (move_uploaded_file($_FILES['receipt']['tmp_name'], $targetFile)) {
        $receipt_path = 'uploads/finances/' . $mesActual . '/' . $filename; 
    }
}

try {
    $stmt = $pdo->prepare("
        INSERT INTO transactions (
            user_id, 
            transaction_type, 
            description, 
            amount, 
            transaction_date, 
            receipt_file, 
            status, 
            created_at
        ) 
        VALUES (?, 'expense', ?, ?, ?, ?, 'pending', NOW())
    ");
    
    $stmt->execute([$user_id, $description, $amount, $date, $receipt_path]);
    
    echo json_encode(['success' => true, 'message' => 'Gasto enviado a revisión.']);

} catch (Exception $e) {
    error_log("Error Caja Chica: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error al guardar en base de datos.']);
}
?>