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

$id = $_GET['id'] ?? (isset($_POST['id']) ? $_POST['id'] : '');
$trans = ['description' => 'Transacción Desconocida'];

if($id){
    try {
        // Corregido: 'finances' a 'transactions'
        $stmt = $pdo->prepare("SELECT description FROM transactions WHERE id = ?");
        $stmt->execute([$id]);
        $result = $stmt->fetch();
        if($result) $trans = $result;
    } catch(Exception $e) {}
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['receipt_file'])) {
    $id = $_POST['id'];
    
    $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[date('n')];
    
    $uploadDir = "../uploads/finances/" . $mesActual . "/"; 
    
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $extension = pathinfo($_FILES['receipt_file']['name'], PATHINFO_EXTENSION);
    $fileName = "mobile_" . uniqid() . "." . $extension; 
    $targetPath = $uploadDir . $fileName;
    
    $dbPath = "uploads/finances/" . $mesActual . "/" . $fileName;
    
    if (move_uploaded_file($_FILES['receipt_file']['tmp_name'], $targetPath)) {
        // Corregido: 'finances' a 'transactions'
        $sql = "UPDATE transactions SET receipt_file = ? WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$dbPath, $id]);
        
        echo "<!DOCTYPE html>
        <html>
        <head>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <script src='https://cdn.tailwindcss.com'></script>
            <script src='https://unpkg.com/lucide@latest'></script>
        </head>
        <body class='bg-[var(--color-highlight)] flex flex-col items-center justify-center min-h-screen p-4 text-center'>
            <div class='bg-[var(--color-highlight)] p-8 rounded-full shadow-lg mb-6'>
                <i data-lucide='square-check-big' class='w-16 h-16 text-[var(--color-primary)]'></i>
            </div>
            <h1 class='text-2xl font-black text-[var(--color-primary)] mb-2'>¡COMPROBANTE SUBIDO!</h1>
            <p class='text-gray-600'>Ya Puedes Cerrar Esta Ventana</p>
            <script>
                lucide.createIcons();
                // setTimeout(()=>{ window.close() }, 1000);
            </script>
        </body>
        </html>";
        exit;
    } else {
        echo "Error al guardar en: " . $targetPath;
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subir Comprobante Financiero</title>
    
    <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <script src="https://cdn.tailwindcss.com"></script>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="../style.css">
    <script src="../files/header-manager.js"></script>
    
</head>
<body class="bg-gray-900 flex items-center justify-center min-h-screen p-4">
    
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md text-center overflow-hidden">
        
        <div class="bg-[var(--color-secondary)] p-5 border-b border-gray-200 shadow z-20">
            <h2 class="text-2xl font-black text-[var(--color-highlight)] uppercase flex items-center justify-center gap-2 leading-none">
                <i data-lucide="save" class="w-6 h-6 text-white"></i>
                SUBIR COMPROBANTE 
            </h2>
        </div>
        
        <div class="p-6">
            <div class="bg-gray-50 p-4 rounded-lg border-l-4 border-[var(--color-highlight)] text-left shadow-sm mb-6">
                <p class="text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Para la transacción:</p>
                <p class="text-lg font-black text-[var(--color-primary)] uppercase leading-tight">
                    <?php echo htmlspecialchars($trans['description']); ?>
                </p>
            </div>
            
            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <input type="hidden" name="id" value="<?php echo htmlspecialchars($id); ?>">
                
                <label class="block w-full p-8 border-4 border-dashed border-gray-300 rounded-xl bg-gray-50 cursor-pointer hover:bg-white hover:border-[var(--color-highlight)] transition-all duration-200 group active:scale-95 transform">
                    <div class="flex flex-col items-center">
                        
                        <div class="mb-3 transform group-hover:scale-110 transition-transform duration-200">
                            <i data-lucide="camera" class="w-14 h-14 text-[var(--color-secondary)]" stroke-width="1.5"></i>
                        </div>
                        
                        <span class="block text-[var(--color-primary)] font-black text-xl uppercase mb-1 group-hover:text-[var(--color-highlight)] transition-colors">
                            TOMAR FOTO
                        </span>
                        
                        <span class="text-xs font-black text-gray-400 uppercase tracking-wide">
                            o seleccionar de galería
                        </span>
                    </div>
                    
                    <input type="file" name="receipt_file" accept="image/*,application/pdf" capture="environment" class="hidden" onchange="this.form.submit()">
                </label>
            </form>
        </div>
        
        <div class="bg-gray-100 p-3 border-t border-gray-200">
            <p class="text-[10px] font-black text-gray-400 uppercase tracking-widest">
                SISTEMA DE GESTIÓN FINANCIERA
            </p>
        </div>
    </div>

    <script>
        lucide.createIcons();
    </script>
</body>
</html>