<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

$root = dirname(__DIR__, 2);
require $root . '/core/config.php';
require $root . '/core/DB.php';

$action = $_GET['action'] ?? 'list';

if(isset($_POST['login'])){
    if($_POST['u']==$config['admin']['user'] && hash('sha256', $_POST['p'])==$config['admin']['pass']){ 
        $_SESSION['admin']=1; 
        header('Location: index.php');
        exit;
    }
    $error = 'Credenciales incorrectas';
}

if(isset($_GET['logout'])){
    session_destroy();
    header('Location: index.php');
    exit;
}

if(!isset($_SESSION['admin'])){ 
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Cuboid Store</title>
    <link href="../styles.css" rel="stylesheet">
    <script>
        if (localStorage.getItem('darkMode') === 'true' || (!localStorage.getItem('darkMode') && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
        }
    </script>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <h1>Admin Login</h1>
            <?php if(isset($error)): ?>
            <p style="color: #ef4444; margin-bottom: 1rem;"><?=$error?></p>
            <?php endif; ?>
            <form method="post">
                <input name="u" type="text" class="form-input" placeholder="Usuario" required>
                <input name="p" type="password" class="form-input" placeholder="Contraseña" required>
                <button type="submit" name="login" class="btn btn-primary" style="width: 100%;">Ingresar</button>
            </form>
        </div>
    </div>
</body>
</html>
<?php 
    exit; 
}

if ($action === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("INSERT INTO products (name, description, price, file, image, downloads_limit, active) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $_POST['name'],
        $_POST['description'],
        (int)$_POST['price'],
        $_POST['file'],
        $_POST['image'] ?? '',
        (int)($_POST['downloads_limit'] ?? 3),
        isset($_POST['active']) ? 1 : 0
    ]);
    header('Location: index.php?success=created');
    exit;
}

if ($action === 'edit' && isset($_GET['id']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("UPDATE products SET name=?, description=?, price=?, file=?, image=?, downloads_limit=?, active=? WHERE id=?");
    $stmt->execute([
        $_POST['name'],
        $_POST['description'],
        (int)$_POST['price'],
        $_POST['file'],
        $_POST['image'] ?? '',
        (int)($_POST['downloads_limit'] ?? 3),
        isset($_POST['active']) ? 1 : 0,
        $_GET['id']
    ]);
    header('Location: index.php?success=updated');
    exit;
}

if ($action === 'delete' && isset($_GET['id'])) {
    $stmt = $pdo->prepare("DELETE FROM products WHERE id=?");
    $stmt->execute([$_GET['id']]);
    header('Location: index.php?success=deleted');
    exit;
}

if ($action === 'toggle' && isset($_GET['id'])) {
    $stmt = $pdo->prepare("UPDATE products SET active = NOT active WHERE id=?");
    $stmt->execute([$_GET['id']]);
    header('Location: index.php');
    exit;
}

$products = $pdo->query("SELECT * FROM products ORDER BY id DESC")->fetchAll();
$payments = $pdo->query("SELECT p.*, pr.name as product_name FROM payments p LEFT JOIN products pr ON p.product_id = pr.id ORDER BY p.id DESC LIMIT 20")->fetchAll();
$downloads = $pdo->query("SELECT d.*, p.name as product_name FROM downloads d LEFT JOIN products p ON d.product_id = p.id ORDER BY d.id DESC LIMIT 20")->fetchAll();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Cuboid Store</title>
    <link href="../styles.css" rel="stylesheet">
    <script>
        if (localStorage.getItem('darkMode') === 'true' || (!localStorage.getItem('darkMode') && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
        }
    </script>
    <style>
        .admin-layout { display: flex; min-height: 100vh; }
        .admin-sidebar { width: 250px; background: var(--bg-primary); border-right: 1px solid var(--border-color); padding: 1.5rem; }
        .admin-main { flex: 1; padding: 2rem; overflow-y: auto; }
        .admin-menu { list-style: none; padding: 0; margin: 0; }
        .admin-menu li { margin-bottom: 0.5rem; }
        .admin-menu a { display: block; padding: 0.75rem 1rem; color: var(--text-secondary); text-decoration: none; border-radius: 8px; transition: all 0.2s; }
        .admin-menu a:hover, .admin-menu a.active { background: var(--bg-secondary); color: var(--text-primary); }
        .admin-table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
        .admin-table th, .admin-table td { padding: 1rem; text-align: left; border-bottom: 1px solid var(--border-color); }
        .admin-table th { font-weight: 600; color: var(--text-secondary); font-size: 0.875rem; text-transform: uppercase; }
        .admin-table tr:hover { background: var(--bg-secondary); }
        .badge { display: inline-block; padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; }
        .badge-success { background: #dcfce7; color: #166534; }
        .badge-error { background: #fee2e2; color: #991b1b; }
        .badge-warning { background: #fef3c7; color: #92400e; }
        .btn-sm { padding: 0.375rem 0.75rem; font-size: 0.875rem; border-radius: 6px; text-decoration: none; display: inline-block; }
        .btn-danger { background: #ef4444; color: white; }
        .btn-danger:hover { background: #dc2626; }
        .alert { padding: 1rem; border-radius: 8px; margin-bottom: 1.5rem; }
        .alert-success { background: #dcfce7; color: #166534; }
        .modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center; }
        .modal.active { display: flex; }
        .modal-content { background: var(--bg-card); border-radius: 16px; padding: 2rem; max-width: 500px; width: 90%; max-height: 90vh; overflow-y: auto; }
        .form-group { margin-bottom: 1rem; }
        .form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; }
        .form-group input[type="text"], .form-group input[type="number"], .form-group textarea { width: 100%; padding: 0.75rem; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-secondary); color: var(--text-primary); }
        .form-group input:focus, .form-group textarea:focus { outline: none; border-color: #3b82f6; }
        .checkbox-label { display: flex; align-items: center; gap: 0.5rem; cursor: pointer; }
        .tabs { display: flex; gap: 1rem; border-bottom: 1px solid var(--border-color); margin-bottom: 1.5rem; }
        .tab { padding: 0.75rem 1rem; cursor: pointer; border-bottom: 2px solid transparent; color: var(--text-secondary); }
        .tab.active { border-bottom-color: #3b82f6; color: var(--text-primary); }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .empty-state { text-align: center; padding: 3rem; color: var(--text-secondary); }
        @media (max-width: 768px) {
            .admin-layout { flex-direction: column; }
            .admin-sidebar { width: 100%; border-right: none; border-bottom: 1px solid var(--border-color); }
            .admin-table { font-size: 0.875rem; }
            .admin-table th, .admin-table td { padding: 0.5rem; }
        }
    </style>
</head>
<body>
    <div class="admin-layout">
        <aside class="admin-sidebar">
            <a href="index.php" class="logo" style="display: block; margin-bottom: 2rem; font-size: 1.25rem; font-weight: 700;">Cuboid Admin</a>
            <ul class="admin-menu">
                <li><a href="#" class="tab-link active" data-tab="products">Productos</a></li>
                <li><a href="#" class="tab-link" data-tab="payments">Pagos</a></li>
                <li><a href="#" class="tab-link" data-tab="downloads">Descargas</a></li>
                <li><a href="?logout=1" style="margin-top: 2rem; color: #ef4444;">Cerrar sesión</a></li>
            </ul>
            <button class="dark-toggle" onclick="toggleDarkMode()" style="margin-top: 2rem;">
                <svg class="sun-icon" width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"/></svg>
                <svg class="moon-icon" width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="display:none"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"/></svg>
            </button>
        </aside>

        <main class="admin-main">
            <?php if(isset($_GET['success'])): ?>
            <div class="alert alert-success">
                <?php 
                $messages = [
                    'created' => 'Producto creado exitosamente',
                    'updated' => 'Producto actualizado',
                    'deleted' => 'Producto eliminado'
                ];
                echo $messages[$_GET['success']] ?? 'Operación exitosa';
                ?>
            </div>
            <?php endif; ?>

            <div id="products" class="tab-content active">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                    <h1 style="font-size: 1.5rem; font-weight: 600;">Productos</h1>
                    <button onclick="openModal('add-product')" class="btn btn-primary">+ Nuevo Producto</button>
                </div>

                <?php if(empty($products)): ?>
                <div class="empty-state">No hay productos. Crea el primero.</div>
                <?php else: ?>
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Nombre</th>
                            <th>Precio</th>
                            <th>Archivo</th>
                            <th>Estado</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($products as $p): ?>
                        <tr>
                            <td><?=$p['id']?></td>
                            <td><?=htmlspecialchars($p['name'])?></td>
                            <td>$<?=number_format($p['price'], 0, ',', '.')?> CLP</td>
                            <td style="font-size: 0.75rem; max-width: 150px; overflow: hidden; text-overflow: ellipsis;"><?=htmlspecialchars($p['file'])?></td>
                            <td>
                                <span class="badge <?=$p['active'] ? 'badge-success' : 'badge-error'?>">
                                    <?=$p['active'] ? 'Activo' : 'Oculto'?>
                                </span>
                            </td>
                            <td>
                                <a href="?action=toggle&id=<?=$p['id']?>" class="btn-sm btn-secondary" title="<?=$p['active'] ? 'Ocultar' : 'Mostrar'?>">
                                    <?=$p['active'] ? '👁️' : '🙈'?>
                                </a>
                                <a href="?action=edit&id=<?=$p['id']?>" class="btn-sm btn-secondary" style="margin: 0 0.25rem;">✏️</a>
                                <a href="?action=delete&id=<?=$p['id']?>" class="btn-sm btn-danger" onclick="return confirm('¿Eliminar producto?')">🗑️</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>

            <div id="payments" class="tab-content">
                <h1 style="font-size: 1.5rem; font-weight: 600; margin-bottom: 1.5rem;">Pagos Recientes</h1>
                <?php if(empty($payments)): ?>
                <div class="empty-state">No hay pagos aún</div>
                <?php else: ?>
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Producto</th>
                            <th>Email</th>
                            <th>Monto</th>
                            <th>Estado</th>
                            <th>MP ID</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($payments as $pay): ?>
                        <tr>
                            <td><?=$pay['id']?></td>
                            <td><?=htmlspecialchars($pay['product_name'] ?? 'N/A')?></td>
                            <td><?=htmlspecialchars($pay['email'])?></td>
                            <td>$<?=number_format($pay['amount'], 0, ',', '.')?> CLP</td>
                            <td>
                                <span class="badge <?=in_array($pay['status'], ['approved','completed']) ? 'badge-success' : 'badge-warning'?>">
                                    <?=$pay['status']?>
                                </span>
                            </td>
                            <td style="font-size: 0.75rem;"><?=htmlspecialchars($pay['mp_payment_id'])?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>

            <div id="downloads" class="tab-content">
                <h1 style="font-size: 1.5rem; font-weight: 600; margin-bottom: 1.5rem;">Descargas Recientes</h1>
                <?php if(empty($downloads)): ?>
                <div class="empty-state">No hay descargas aún</div>
                <?php else: ?>
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Producto</th>
                            <th>Email</th>
                            <th>Límite</th>
                            <th>Usadas</th>
                            <th>Expira</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($downloads as $d): ?>
                        <tr>
                            <td><?=$d['id']?></td>
                            <td><?=htmlspecialchars($d['product_name'] ?? 'N/A')?></td>
                            <td><?=htmlspecialchars($d['email'])?></td>
                            <td><?=$d['downloads_limit']?></td>
                            <td><?=$d['downloads_used']?></td>
                            <td><?=date('d/m/Y H:i', strtotime($d['expires_at']))?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <div id="add-product" class="modal">
        <div class="modal-content">
            <h2 style="margin-bottom: 1.5rem;">Nuevo Producto</h2>
            <form method="post" action="?action=add">
                <div class="form-group">
                    <label>Nombre</label>
                    <input type="text" name="name" required>
                </div>
                <div class="form-group">
                    <label>Descripción</label>
                    <textarea name="description" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label>Precio (CLP)</label>
                    <input type="number" name="price" required min="0">
                </div>
                <div class="form-group">
                    <label>Archivo (ruta)</label>
                    <input type="text" name="file" placeholder="/home/marcatum/storage/files/archivo.zip" required>
                </div>
                <div class="form-group">
                    <label>Imagen (URL)</label>
                    <input type="text" name="image" placeholder="https://... o /storage/images/.jpg">
                    <small style="color: var(--text-secondary);">Formatos: JPG, PNG, WebP, SVG, AVIF</small>
                </div>
                <div class="form-group">
                    <label>Límite de descargas</label>
                    <input type="number" name="downloads_limit" value="3" min="1" max="100">
                </div>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="active" checked> Activo
                    </label>
                </div>
                <div style="display: flex; gap: 1rem;">
                    <button type="submit" class="btn btn-primary" style="flex:1;">Crear</button>
                    <button type="button" onclick="closeModal('add-product')" class="btn btn-secondary" style="flex:1;">Cancelar</button>
                </div>
            </form>
        </div>
    </div>

    <?php if($action === 'edit' && isset($_GET['id'])): 
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$_GET['id']]);
        $editProduct = $stmt->fetch();
    ?>
    <div id="edit-product" class="modal active">
        <div class="modal-content">
            <h2 style="margin-bottom: 1.5rem;">Editar Producto</h2>
            <form method="post" action="?action=edit&id=<?=$_GET['id']?>">
                <div class="form-group">
                    <label>Nombre</label>
                    <input type="text" name="name" value="<?=htmlspecialchars($editProduct['name'])?>" required>
                </div>
                <div class="form-group">
                    <label>Descripción</label>
                    <textarea name="description" rows="3"><?=htmlspecialchars($editProduct['description'])?></textarea>
                </div>
                <div class="form-group">
                    <label>Precio (CLP)</label>
                    <input type="number" name="price" value="<?=$editProduct['price']?>" required min="0">
                </div>
                <div class="form-group">
                    <label>Archivo (ruta)</label>
                    <input type="text" name="file" value="<?=htmlspecialchars($editProduct['file'])?>" required>
                </div>
                <div class="form-group">
                    <label>Imagen (URL)</label>
                    <input type="text" name="image" value="<?=htmlspecialchars($editProduct['image'] ?? '')?>" placeholder="https://... o /storage/images/.jpg">
                    <small style="color: var(--text-secondary);">Formatos: JPG, PNG, WebP, SVG, AVIF</small>
                </div>
                <div class="form-group">
                    <label>Límite de descargas</label>
                    <input type="number" name="downloads_limit" value="<?=$editProduct['downloads_limit'] ?? 3?>" min="1" max="100">
                </div>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="active" <?=($editProduct['active'] ?? 1) ? 'checked' : ''?>> Activo
                    </label>
                </div>
                <div style="display: flex; gap: 1rem;">
                    <button type="submit" class="btn btn-primary" style="flex:1;">Guardar</button>
                    <a href="index.php" class="btn btn-secondary" style="flex:1; text-align: center; line-height: 2.5rem;">Cancelar</a>
                </div>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <script>
        document.querySelectorAll('.tab-link').forEach(link => {
            link.addEventListener('click', e => {
                e.preventDefault();
                document.querySelectorAll('.tab-link').forEach(l => l.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
                link.classList.add('active');
                document.getElementById(link.dataset.tab).classList.add('active');
            });
        });

        function openModal(id) { document.getElementById(id).classList.add('active'); }
        function closeModal(id) { document.getElementById(id).classList.remove('active'); }

        function toggleDarkMode() {
            document.documentElement.classList.toggle('dark');
            localStorage.setItem('darkMode', document.documentElement.classList.contains('dark'));
            updateIcons(document.documentElement.classList.contains('dark'));
        }
        function updateIcons(isDark) {
            document.querySelector('.sun-icon').style.display = isDark ? 'none' : 'block';
            document.querySelector('.moon-icon').style.display = isDark ? 'block' : 'none';
        }
        updateIcons(document.documentElement.classList.contains('dark'));
    </script>
</body>
</html>
