<?php
require_once __DIR__ . '/../includes/config.php';

$page_title = 'Comenzi';

require_once __DIR__ . '/../includes/header.php';

// Get order statuses
$statuses_result = $db->query("SELECT * FROM order_statuses ORDER BY name");
$statuses = [];
while ($status = $statuses_result->fetch_assoc()) {
    $statuses[] = $status;
}

// Get categories
$categories_result = $db->query("SELECT DISTINCT c.id, c.name FROM categories c 
    JOIN products p ON c.id = p.category_id 
    JOIN order_items oi ON p.id = oi.product_id 
    ORDER BY c.name");
$categories = [];
while ($cat = $categories_result->fetch_assoc()) {
    $categories[] = $cat;
}

// Get filters
$search = $_GET['q'] ?? '';
$status_filter = $_GET['status'] ?? '';
$category_filter = $_GET['category'] ?? '';
$price_min = $_GET['price_min'] ?? '';
$price_max = $_GET['price_max'] ?? '';

$search = escape(trim($search));

// Build query
$query = "SELECT o.*, c.first_name, c.last_name, c.phone, os.name as status_name, os.color as status_color
          FROM orders o
          JOIN clients c ON o.client_id = c.id
          JOIN order_statuses os ON o.status_id = os.id
          WHERE 1=1";

if (!empty($search)) {
    $query .= " AND (c.first_name LIKE '%$search%' OR c.last_name LIKE '%$search%' OR c.phone LIKE '%$search%' OR c.email LIKE '%$search%')";
}

if (!empty($status_filter)) {
    $status_filter = (int)$status_filter;
    $query .= " AND o.status_id = $status_filter";
}

// Category filter
if (!empty($category_filter)) {
    $category_filter = (int)$category_filter;
    $query .= " AND o.id IN (
        SELECT oi.order_id FROM order_items oi
        JOIN products p ON oi.product_id = p.id
        WHERE p.category_id = $category_filter
    )";
}

// Price filters
if (!empty($price_min)) {
    $price_min = (float)$price_min;
    $query .= " AND o.id IN (
        SELECT oi.order_id FROM order_items oi
        GROUP BY oi.order_id HAVING SUM(oi.price * oi.quantity) >= $price_min
    )";
}

if (!empty($price_max)) {
    $price_max = (float)$price_max;
    $query .= " AND o.id IN (
        SELECT oi.order_id FROM order_items oi
        GROUP BY oi.order_id HAVING SUM(oi.price * oi.quantity) <= $price_max
    )";
}

$query .= " ORDER BY o.created_at DESC";

$result = $db->query($query);
$orders = [];
if ($result && $result->num_rows > 0) {
    while ($order = $result->fetch_assoc()) {
        $orders[] = $order;
    }
}
?>

<form method="GET" style="margin-bottom:16px">
    <div style="display:grid;grid-template-columns:2fr 1fr 1fr 1fr 1fr auto auto;gap:10px;align-items:end">
        <div>
            <label style="display:block;font-size:11px;font-weight:700;color:var(--text2);text-transform:uppercase;margin-bottom:6px">Cauta</label>
            <input type="text" name="q" value="<?php echo htmlspecialchars($_GET['q'] ?? ''); ?>" placeholder="Nume, telefon, email..." style="width:100%;padding:8px 12px;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px">
        </div>
        
        <div>
            <label style="display:block;font-size:11px;font-weight:700;color:var(--text2);text-transform:uppercase;margin-bottom:6px">Status</label>
            <select name="status" style="width:100%;padding:8px 12px;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px">
                <option value="">Toate</option>
                <?php foreach ($statuses as $s): ?>
                    <option value="<?php echo $s['id']; ?>" <?php echo ($_GET['status'] ?? '') == $s['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($s['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div>
            <label style="display:block;font-size:11px;font-weight:700;color:var(--text2);text-transform:uppercase;margin-bottom:6px">Categorie</label>
            <select name="category" style="width:100%;padding:8px 12px;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px">
                <option value="">Toate</option>
                <?php foreach ($categories as $cat): ?>
                    <option value="<?php echo $cat['id']; ?>" <?php echo ($_GET['category'] ?? '') == $cat['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div>
            <label style="display:block;font-size:11px;font-weight:700;color:var(--text2);text-transform:uppercase;margin-bottom:6px">Pret min</label>
            <input type="number" name="price_min" value="<?php echo htmlspecialchars($_GET['price_min'] ?? ''); ?>" placeholder="0" step="0.01" style="width:100%;padding:8px 12px;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px">
        </div>
        
        <div>
            <label style="display:block;font-size:11px;font-weight:700;color:var(--text2);text-transform:uppercase;margin-bottom:6px">Pret max</label>
            <input type="number" name="price_max" value="<?php echo htmlspecialchars($_GET['price_max'] ?? ''); ?>" placeholder="999999" step="0.01" style="width:100%;padding:8px 12px;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px">
        </div>
        
        <button type="submit" class="btn btn-primary">🔍 Filtreaza</button>
        <a href="<?php echo APP_URL; ?>/admin/orders.php" class="btn btn-ghost" style="text-decoration:none;text-align:center">↻ Reset</a>
    </div>
</form>

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
    <div style="color:var(--text2);font-size:13px">
        <?php echo count($orders); ?> comenzi
    </div>
    <a href="<?php echo APP_URL; ?>/admin/order-form.php" class="btn btn-primary">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" width="15" height="15"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
        Comandă nouă
    </a>
</div>

<div class="card">
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Client</th>
                    <th>Telefon</th>
                    <th>Produse</th>
                    <th>Livrare</th>
                    <th>Total</th>
                    <th>Status</th>
                    <th>Data</th>
                    <th style="text-align:right">Acțiuni</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($orders)): ?>
                    <tr>
                        <td colspan="9">
                            <div class="empty-state">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/></svg>
                                <h3>Nicio comandă</h3>
                                <p>Apasă „Comandă nouă"</p>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($orders as $order): ?>
                        <?php
                        // Calculate order total
                        $item_result = $db->query("SELECT SUM(price * quantity) as subtotal FROM order_items WHERE order_id = " . $order['id']);
                        $subtotal = ($item_result->fetch_assoc()['subtotal'] ?? 0);
                        
                        // Apply discount
                        $discount = 0;
                        if ($order['discount_id']) {
                            $disc_result = $db->query("SELECT * FROM discounts WHERE id = " . $order['discount_id']);
                            if ($disc = $disc_result->fetch_assoc()) {
                                $discount = $disc['type'] === 'percent' ? round($subtotal * $disc['value'] / 100) : $disc['value'];
                            }
                        }
                        
                        $delivery = $order['delivery_enabled'] ? $order['delivery_price'] : 0;
                        $total = max(0, $subtotal - $discount + $delivery);
                        $client_name = getClientName($order['first_name'], $order['last_name']);
                        
                        // Get item count
                        $item_count_result = $db->query("SELECT COUNT(*) as count FROM order_items WHERE order_id = " . $order['id']);
                        $item_count = $item_count_result->fetch_assoc()['count'];
                        ?>
                        <tr>
                            <td style="color:var(--text3);font-size:12px">#<?php echo $order['id']; ?></td>
                            <td><strong><?php echo htmlspecialchars($client_name); ?></strong></td>
                            <td class="td-muted"><?php echo htmlspecialchars($order['phone'] ?: '—'); ?></td>
                            <td class="td-muted"><?php echo $item_count; ?> prod.</td>
                            <td><?php echo $order['delivery_enabled'] ? '<span class="badge badge-blue">+' . number_format($order['delivery_price'], 2, '.', '') . ' lei</span>' : '<span style="color:var(--text3);font-size:12px">Ridicare</span>'; ?></td>
                            <td style="font-weight:700;color:var(--accent)"><?php echo number_format($total, 2, '.', ''); ?> lei</td>
                            <td><span class="badge" style="background:<?php echo $order['status_color']; ?>22;color:<?php echo $order['status_color']; ?>"><span style="background:<?php echo $order['status_color']; ?>;width:5px;height:5px;border-radius:50%;display:inline-block;margin-right:4px"></span><?php echo htmlspecialchars($order['status_name']); ?></span></td>
                            <td class="td-muted"><?php echo formatDate($order['order_date']); ?></td>
                            <td>
                                <div class="td-actions">
                                    <a href="<?php echo APP_URL; ?>/admin/order-preview.php?id=<?php echo $order['id']; ?>" class="btn btn-ghost btn-sm">👁 Preview</a>
                                    <a href="<?php echo APP_URL; ?>/admin/order-form.php?id=<?php echo $order['id']; ?>" class="btn btn-ghost btn-sm">✎ Edit</a>
                                    <form method="POST" action="<?php echo APP_URL; ?>/api/delete-order.php" style="display:inline" onsubmit="return confirm('Ștergi comanda #<?php echo $order['id']; ?>?')">
                                        <input type="hidden" name="id" value="<?php echo $order['id']; ?>">
                                        <button type="submit" class="btn btn-danger btn-sm">✕</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>



<?php
require_once __DIR__ . '/../includes/footer.php';
?>
