<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../config/security.php';
require_admin();

$id = (int)($_GET['id'] ?? 0);
$stmt = db()->prepare('SELECT * FROM orders WHERE id = :id LIMIT 1');
$stmt->execute(['id' => $id]);
$order = $stmt->fetch();
if (!$order) {
    header('Location: orders.php');
    exit;
}

// Procesar cambio de estado
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $newStatus = clean_input($_POST['status']);
    $oldStatus = $order['status'];
    
    if ($newStatus !== $oldStatus) {
        $stmt = db()->prepare('UPDATE orders SET status = ? WHERE id = ?');
        $stmt->execute([$newStatus, $id]);
        
        // 1. Registrar en historial
        add_order_history($id, $newStatus, "Cambio de estado manual desde el panel admin.");
        
        // 2. 🔥 ENVIAR CORREO AUTOMÁTICO
        send_order_status_email($id, $newStatus);

        // 3. 🔄 DEVOLVER STOCK SI SE CANCELA
        if ($newStatus === 'Cancelado') {
            return_order_stock($id);
        }

        redirect_with_message("order-view.php?id=$id", "Estado actualizado a $newStatus, historial registrado y cliente notificado.");
    }
}

$stmtItems = db()->prepare('SELECT * FROM order_items WHERE order_id = :order_id');
$stmtItems->execute(['order_id' => $order['id']]);
$items = $stmtItems->fetchAll();

// Obtener historial
$history = db()->query("SELECT * FROM order_status_history WHERE order_id = $id ORDER BY created_at DESC")->fetchAll();

$statuses = [
    'Pendiente' => '⏳ Pendiente',
    'Confirmado' => '💳 Confirmado',
    'Procesando' => '⚙️ Procesando',
    'En Embalaje' => '📦 En Embalaje',
    'En Camino' => '🚚 En Camino',
    'Entregado' => '✅ Entregado',
    'Cancelado' => '❌ Cancelado'
];

$title = 'Orden #' . $order['order_number'] . ' - BICHOTTA';
admin_header($title);
?>

<div class="dashboard-header" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:30px;">
    <div>
        <h1>Orden #<?php echo sanitize($order['order_number']); ?></h1>
        <p class="text-muted">Gestiona el ciclo de vida del pedido.</p>
    </div>
    <a href="orders.php" class="btn btn-secondary">Volver al listado</a>
</div>

<div class="crm-grid" style="display:grid; grid-template-columns: 2fr 1fr; gap:30px;">
    
    <div class="card-column" style="display:flex; flex-direction:column; gap:30px;">
        <!-- PRODUCTOS -->
        <div class="card" style="padding:0; overflow:hidden;">
            <h3 style="padding:25px 25px 0;">Artículos del Pedido</h3>
            <table class="table">
                <thead>
                    <tr><th>Producto</th><th>Cant.</th><th>Precio</th><th style="text-align:right;">Total</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $item): ?>
                    <tr>
                        <td><strong><?php echo sanitize($item['product_name']); ?></strong></td>
                        <td><?php echo (int)$item['quantity']; ?></td>
                        <td>$<?php echo number_format($item['price'], 0, ',', '.'); ?></td>
                        <td style="text-align:right;"><strong>$<?php echo number_format($item['total'], 0, ',', '.'); ?></strong></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div style="padding:25px; background:#f9fafb; display:flex; justify-content:flex-end;">
                <div style="text-align:right;">
                    <p class="text-muted">Total del Pedido</p>
                    <p style="font-size:1.8rem; font-weight:900; color:var(--admin-accent);">$<?php echo number_format($order['total'], 0, ',', '.'); ?></p>
                </div>
            </div>
        </div>

        <!-- INFO CLIENTE -->
        <div class="card">
            <h3>📍 Datos de Entrega</h3>
            <div class="form-grid" style="grid-template-columns: 1fr 1fr; gap:20px; margin-top:20px;">
                <div><strong>Cliente:</strong><br><?php echo sanitize($order['customer_name']); ?></div>
                <div><strong>Teléfono:</strong><br><?php echo sanitize($order['phone']); ?></div>
                <div style="grid-column: span 2;"><strong>Dirección:</strong><br><?php echo sanitize($order['address']); ?>, <?php echo sanitize($order['comuna']); ?>, <?php echo sanitize($order['region']); ?></div>
                <div style="grid-column: span 2;"><strong>Notas:</strong><br><em class="text-muted"><?php echo sanitize($order['notes'] ?: 'Sin notas adicionales.'); ?></em></div>
            </div>
        </div>
    </div>

    <div class="card-column" style="display:flex; flex-direction:column; gap:30px;">
        <!-- ESTADO DEL PEDIDO (MERCADO LIBRE STYLE) -->
        <div class="card" style="border-top: 4px solid var(--admin-accent);">
            <h3>🚢 Estado del Envío</h3>
            <form method="post" style="margin-top:20px;">
                <input type="hidden" name="update_status" value="1">
                <div class="input-group">
                    <label>Cambiar Estatus</label>
                    <select name="status" style="padding:15px; font-weight:700;">
                        <?php foreach ($statuses as $val => $label): ?>
                            <option value="<?php echo $val; ?>" <?php echo $order['status'] === $val ? 'selected' : ''; ?>><?php echo $label; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary" style="width:100%; margin-top:15px; padding:18px;">ACTUALIZAR ESTADO</button>
            </form>

            <div style="margin-top:30px;">
                <small class="text-muted">Línea de tiempo:</small>
                <div style="margin-top:15px; display:flex; flex-direction:column; gap:15px;">
                    <?php 
                    $order_steps = ['Pendiente', 'Procesando', 'En Embalaje', 'En Camino', 'Entregado'];
                    $current_found = false;
                    foreach ($order_steps as $step): 
                        $is_current = ($order['status'] === $step);
                        $is_past = !$is_current && !$current_found;
                        if ($is_current) $current_found = true;
                    ?>
                        <div style="display:flex; align-items:center; gap:10px; opacity: <?php echo ($is_current || $is_past) ? '1' : '0.3'; ?>;">
                            <div style="width:12px; height:12px; border-radius:50%; background: <?php echo $is_current ? 'var(--admin-accent)' : ($is_past ? '#10B981' : '#ccc'); ?>;"></div>
                            <span style="font-size:0.85rem; font-weight: <?php echo $is_current ? '800' : '500'; ?>;"><?php echo $statuses[$step]; ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- PAGO -->
        <div class="card">
            <h3>💰 Información de Pago</h3>
            <p style="margin-top:15px;"><strong>Método:</strong> <?php echo strtoupper($order['payment_method']); ?></p>
            <p><strong>Estado:</strong> <span class="status-pill <?php echo $order['payment_status'] === 'Aprobado' ? 'pill-success' : 'pill-warning'; ?>"><?php echo $order['payment_status']; ?></span></p>
        </div>
    </div>

</div>

<?php admin_footer(); ?>
