<?php
session_start();

// Authentication
$password = 'admin123';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    if ($_POST['password'] === $password) {
        $_SESSION['admin_logged_in'] = true;
        header('Location: index.php');
        exit;
    } else {
        $error = 'Contraseña incorrecta';
    }
}

$is_logged_in = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;

// Read orders
$orders = [];
if ($is_logged_in) {
    $pedidos_file = '../pedidos.txt';
    if (file_exists($pedidos_file)) {
        $lines = file($pedidos_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            $parts = explode(' - ', $line);
            if (count($parts) >= 5) {
                $orders[] = [
                    'date' => $parts[0],
                    'name' => $parts[1],
                    'doc' => $parts[2],
                    'phone' => $parts[3],
                    'address' => $parts[4],
                    'ref' => isset($parts[5]) ? $parts[5] : ''
                ];
            } else {
                // fallback for malformed lines
                $orders[] = [
                    'date' => 'N/A',
                    'name' => 'Raw: ' . $line,
                    'doc' => '',
                    'phone' => '',
                    'address' => '',
                    'ref' => ''
                ];
            }
        }
        $orders = array_reverse($orders); // newest first
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Ventas</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 min-h-screen text-gray-800">

<?php if (!$is_logged_in): ?>
    <div class="flex items-center justify-center min-h-screen">
        <div class="bg-white p-8 rounded-lg shadow-md w-full max-w-sm">
            <div class="text-center mb-6">
                <i class="fas fa-shield-alt text-4xl text-blue-700 mb-2"></i>
                <h1 class="text-2xl font-bold text-gray-800">Acceso Admin</h1>
            </div>
            <?php if ($error): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4 text-sm" role="alert">
                    <span class="block sm:inline"><?php echo $error; ?></span>
                </div>
            <?php endif; ?>
            <form method="POST">
                <div class="mb-6">
                    <label class="block text-gray-700 text-sm font-bold mb-2" for="password"><i class="fas fa-lock mr-1"></i> Contraseña</label>
                    <input class="shadow appearance-none border rounded w-full py-3 px-4 text-gray-700 leading-tight focus:outline-none focus:ring-2 focus:ring-blue-500 transition" id="password" type="password" name="password" placeholder="••••••••" required>
                </div>
                <div class="flex items-center justify-between">
                    <button class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-4 rounded focus:outline-none focus:shadow-outline w-full transition flex justify-center items-center" type="submit" name="login">
                        Ingresar <i class="fas fa-arrow-right ml-2"></i>
                    </button>
                </div>
            </form>
        </div>
    </div>
<?php else: ?>
    <!-- Dashboard -->
    <nav class="bg-blue-800 p-4 text-white shadow-md">
        <div class="container mx-auto flex justify-between items-center">
            <h1 class="text-xl font-bold flex items-center"><i class="fas fa-chart-line mr-2"></i> Panel de Ventas</h1>
            <a href="logout.php" class="bg-red-500 hover:bg-red-600 px-4 py-2 rounded text-sm font-semibold transition flex items-center"><i class="fas fa-sign-out-alt mr-1"></i> Salir</a>
        </div>
    </nav>

    <div class="container mx-auto px-4 py-8">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Columna Principal: Pedidos -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="bg-white border-b border-gray-100 px-6 py-5 flex justify-between items-center">
                        <h2 class="text-lg font-bold text-gray-800 flex items-center"><i class="fas fa-shopping-bag text-blue-600 mr-2"></i> Órdenes Recientes</h2>
                        <span class="bg-blue-100 text-blue-800 text-xs font-semibold px-2.5 py-0.5 rounded-full"><?php echo count($orders); ?> pedidos</span>
                    </div>
                    
                    <div class="p-0">
                        <?php if (empty($orders)): ?>
                            <div class="p-10 text-center text-gray-500 flex flex-col items-center">
                                <i class="fas fa-box-open text-4xl mb-3 text-gray-300"></i>
                                <p>No hay órdenes registradas aún.</p>
                            </div>
                        <?php else: ?>
                            <!-- Para escritorio -->
                            <div class="hidden md:block overflow-x-auto">
                                <table class="min-w-full divide-y divide-gray-200">
                                    <thead class="bg-gray-50">
                                        <tr>
                                            <th class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Fecha</th>
                                            <th class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Cliente</th>
                                            <th class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Contacto</th>
                                            <th class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Dirección</th>
                                        </tr>
                                    </thead>
                                    <tbody class="bg-white divide-y divide-gray-100">
                                        <?php foreach ($orders as $order): ?>
                                            <tr class="hover:bg-blue-50 transition-colors">
                                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                                    <i class="far fa-calendar-alt mr-1"></i> <?php echo htmlspecialchars($order['date']); ?>
                                                </td>
                                                <td class="px-6 py-4 whitespace-nowrap">
                                                    <div class="text-sm font-bold text-gray-900"><?php echo htmlspecialchars($order['name']); ?></div>
                                                    <div class="text-xs text-gray-500 mt-1"><i class="fas fa-id-card mr-1 text-gray-400"></i> <?php echo htmlspecialchars($order['doc']); ?></div>
                                                </td>
                                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
                                                    <i class="fas fa-phone-alt text-gray-400 mr-1"></i> <?php echo htmlspecialchars($order['phone']); ?>
                                                </td>
                                                <td class="px-6 py-4 text-sm text-gray-600">
                                                    <div class="flex items-start">
                                                        <i class="fas fa-map-marker-alt text-red-500 mt-1 mr-2"></i>
                                                        <div>
                                                            <?php echo htmlspecialchars($order['address']); ?><br>
                                                            <?php if(trim($order['ref'])): ?>
                                                                <span class="text-xs text-gray-400 bg-gray-100 px-1 py-0.5 rounded inline-block mt-1"><?php echo htmlspecialchars(str_replace('Ref: ', '', $order['ref'])); ?></span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <!-- Para móviles -->
                            <div class="md:hidden divide-y divide-gray-100">
                                <?php foreach ($orders as $order): ?>
                                    <div class="p-5 hover:bg-blue-50 transition-colors">
                                        <div class="flex justify-between items-start mb-2">
                                            <span class="font-bold text-gray-900 text-base"><?php echo htmlspecialchars($order['name']); ?></span>
                                            <span class="text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded-full whitespace-nowrap ml-2"><i class="far fa-clock mr-1"></i><?php echo htmlspecialchars(explode(' ', $order['date'])[0]); ?></span>
                                        </div>
                                        <div class="flex flex-col gap-1.5 mt-3">
                                            <div class="text-sm text-gray-600 flex items-center"><i class="fas fa-id-card text-gray-400 w-5 text-center mr-2"></i> <?php echo htmlspecialchars($order['doc']); ?></div>
                                            <div class="text-sm text-gray-600 flex items-center"><i class="fas fa-phone-alt text-gray-400 w-5 text-center mr-2"></i> <?php echo htmlspecialchars($order['phone']); ?></div>
                                            <div class="text-sm text-gray-600 mt-2 bg-gray-50 p-3 rounded-lg border border-gray-100 flex items-start">
                                                <i class="fas fa-map-marker-alt text-red-500 w-5 text-center mt-1 mr-2"></i> 
                                                <div>
                                                    <?php echo htmlspecialchars($order['address']); ?>
                                                    <?php if(trim($order['ref'])): ?>
                                                        <div class="text-xs text-gray-500 mt-1 italic"><?php echo htmlspecialchars($order['ref']); ?></div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Sidebar: QR -->
            <div>
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden sticky top-4">
                    <div class="bg-white border-b border-gray-100 px-6 py-5">
                        <h2 class="text-lg font-bold text-gray-800 flex items-center"><i class="fas fa-qrcode text-blue-600 mr-2"></i> Configuración QR</h2>
                    </div>
                    <div class="p-6">
                        <div class="mb-6 text-center">
                            <p class="text-sm text-gray-500 mb-3 font-medium">QR Actual en la pasarela:</p>
                            <div class="inline-block p-2 border-2 border-dashed border-gray-300 rounded-xl bg-gray-50 relative min-h-[180px] min-w-[180px] flex items-center justify-center mx-auto shadow-inner">
                                <?php
                                $qr_path = '../assets/img/qr.png';
                                if (file_exists($qr_path)) {
                                    echo '<img src="../assets/img/qr.png?' . time() . '" class="max-w-[200px] h-auto rounded shadow-sm">';
                                } else {
                                    echo '<div class="text-red-500 text-sm text-center flex flex-col items-center"><i class="fas fa-exclamation-circle text-2xl mb-1"></i><span>No hay QR subido.</span></div>';
                                }
                                ?>
                            </div>
                        </div>

                        <form action="upload_qr.php" method="POST" enctype="multipart/form-data" class="border-t border-gray-100 pt-5">
                            <label class="block text-sm font-semibold text-gray-700 mb-3">Subir Nuevo QR (PNG o JPG)</label>
                            <input type="file" name="qr_image" accept="image/png, image/jpeg, image/jpg" required class="block w-full text-sm text-gray-500 file:mr-4 file:py-2.5 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-bold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 mb-5 cursor-pointer transition-colors">
                            <button type="submit" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-4 rounded-lg transition-colors shadow-md flex justify-center items-center">
                                <i class="fas fa-cloud-upload-alt mr-2"></i> Actualizar QR
                            </button>
                        </form>
                        
                        <?php
                        if (isset($_GET['upload'])) {
                            if ($_GET['upload'] == 'success') {
                                echo '<div class="mt-5 p-3 bg-green-50 border border-green-200 text-green-700 text-sm rounded-lg flex items-center"><i class="fas fa-check-circle mr-2 text-green-500"></i> ¡QR actualizado con éxito!</div>';
                            } elseif ($_GET['upload'] == 'error') {
                                echo '<div class="mt-5 p-3 bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg flex items-center"><i class="fas fa-times-circle mr-2 text-red-500"></i> Error al subir. Verifica que sea JPG o PNG válido.</div>';
                            }
                        }
                        ?>
                    </div>
                </div>
            </div>
            
        </div>
    </div>
<?php endif; ?>
</body>
</html>
