<?php
// FILE NÀY: banhang/mobile_views/orders.php

/*
----------------------------------------------------------------------
--- PHẦN 1: LẤY DỮ LIỆU THẬT (TỪ LOGIC CŨ) ---
----------------------------------------------------------------------
*/

// Thiết lập bộ lọc mặc định
$search_code = $_GET['code'] ?? '';
$filter_status = $_GET['status'] ?? 'all_orders';
$from_date = $_GET['from'] ?? date('Y-m-01'); // Mặc định: đầu tháng
$to_date = $_GET['to'] ?? date('Y-m-t');   // Mặc định: cuối tháng

// SAO CHÉP LOGIC TỪ file orders_ajax.php (handle_get_orders_list)
// ---
$status_map = [
    0 => ['text' => 'Khởi tạo', 'class' => 'status-draft'],
    1 => ['text' => 'Hoàn thành', 'class' => 'status-completed'],
];

$base_sql = "FROM cms_orders o 
             LEFT JOIN cms_customers c ON o.customer_id = c.ID 
             LEFT JOIN cms_stores s ON o.store_id = s.id";

$params = [];
$types = "";
$where_conditions = [];

if ($filter_status === 'all') { // Đơn hàng hoàn thành
    $where_conditions[] = "o.order_status = 1";
} elseif ($filter_status === 'draft') { // Đơn hàng khởi tạo
    $where_conditions[] = "o.order_status = 0";
} elseif ($filter_status === 'debt') {
    $where_conditions[] = "o.lack > 0";
} elseif ($filter_status === 'deleted') {
    $where_conditions[] = "o.deleted = 1";
} else {
    $where_conditions[] = "o.deleted = 0";
}

if (!empty($search_code)) { $where_conditions[] = "o.output_code LIKE ?"; $params[] = "%{$search_code}%"; $types .= "s"; }
if (!empty($from_date)) { $where_conditions[] = "o.sell_date >= ?"; $params[] = "{$from_date} 00:00:00"; $types .= "s"; }
if (!empty($to_date)) { $where_conditions[] = "o.sell_date <= ?"; $params[] = "{$to_date} 23:59:59"; $types .= "s"; }

if ($group_id != 1) { // $group_id lấy từ mobile.php
    $where_conditions[] = "o.user_init = ?";
    $params[] = $user_id; // $user_id lấy từ mobile.php
    $types .= "i";
}

$where_sql = "";
if (!empty($where_conditions)) {
    $where_sql = " WHERE " . implode(" AND ", $where_conditions);
}

// 1. Lấy dữ liệu Thẻ Tóm tắt (Summary Cards)
$stmt_summary = $conn->prepare("SELECT COUNT(o.id) as total_orders, SUM(o.total_money) as total_amount, SUM(o.lack) as total_debt " . $base_sql . $where_sql);
if (!empty($types)) {
    $stmt_summary->bind_param($types, ...$params);
}
$stmt_summary->execute();
$summary_row = $stmt_summary->get_result()->fetch_assoc();
$stmt_summary->close();

$total_orders = $summary_row['total_orders'] ?? 0;
$total_amount = $summary_row['total_amount'] ?? 0;
$total_debt = $summary_row['total_debt'] ?? 0;

// 2. Lấy 50 Đơn hàng đầu tiên (List Data)
$sql_data = "SELECT o.ID as id, o.output_code, o.sell_date, o.total_money, o.lack, o.order_status, o.total_quantity,
             COALESCE(c.customer_name, 'Khách lẻ') as customer_name, s.store_name, o.deleted 
             " . $base_sql . $where_sql . " ORDER BY o.ID DESC LIMIT 50"; // Chỉ lấy 50 đơn

$stmt_data = $conn->prepare($sql_data);
if (!empty($types)) {
    $stmt_data->bind_param($types, ...$params);
}
$stmt_data->execute();
$result = $stmt_data->get_result();
$data_rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
$stmt_data->close();

?>

<a href="pos_mobile.php" class="fab">
    <i class="fa-solid fa-plus"></i>
</a>

<div class="card summary-grid">
    <div class="summary-item">
        <span class="label">Số hóa đơn</span>
        <span class="value" style="color: var(--primary-color);"><?php echo number_format($total_orders); ?></span>
    </div>
    <div class="summary-item">
        <span class="label">Tổng tiền</span>
        <span class="value" style="color: var(--text-success);"><?php echo number_format($total_amount, 0, ',', '.'); ?> đ</span>
    </div>
    <div class="summary-item">
        <span class="label">Tổng nợ</span>
        <span class="value" style="color: var(--text-danger);"><?php echo number_format($total_debt, 0, ',', '.'); ?> đ</span>
    </div>
</div>

<div class="card filter-container">
    <form action="mobile.php" method="GET">
        <input type="hidden" name="page" value="orders">
        
        <div class="filter-bar" style="margin-bottom: 12px;">
            <div class="search-box">
                <i class="fa-solid fa-search"></i>
                <input type="text" name="code" placeholder="Tìm mã đơn hàng..." value="<?php echo htmlspecialchars($search_code); ?>">
            </div>
            <button type="submit" class="btn-filter" style="padding: 10px 14px;">
                <i class="fa-solid fa-search"></i>
            </button>
        </div>
        
        <div class="filter-dates">
            <input type="text" id="filter-from-date" name="from" class="form-control" placeholder="Từ ngày" value="<?php echo htmlspecialchars($from_date); ?>">
            <input type="text" id="filter-to-date" name="to" class="form-control" placeholder="Đến ngày" value="<?php echo htmlspecialchars($to_date); ?>">
        </div>
        
        <div class="filter-quick-buttons">
            <button type="button" class="btn-quick-date" data-range="week">Tuần</button>
            <button type="button" class="btn-quick-date" data-range="month">Tháng</button>
            <button type="button" class="btn-quick-date" data-range="quarter">Quý</button>
        </div>
        
        <select name="status" class="form-control" onchange="this.form.submit()">
            <option value="all_orders" <?php echo ($filter_status == 'all_orders') ? 'selected' : ''; ?>>Tất cả (Không xóa)</option>
            <option value="draft" <?php echo ($filter_status == 'draft') ? 'selected' : ''; ?>>Đơn khởi tạo (Nháp)</option>
            <option value="debt" <?php echo ($filter_status == 'debt') ? 'selected' : ''; ?>>Đơn hàng còn nợ</option>
            <option value="deleted" <?php echo ($filter_status == 'deleted') ? 'selected' : ''; ?>>Đơn hàng đã xóa</option>
        </select>
    </form>
</div>

<div class="list-container">
    <?php if (empty($data_rows)): ?>
        <p style="text-align: center; color: var(--text-light); padding: 20px;">Không tìm thấy đơn hàng nào.</p>
    <?php endif; ?>

    <?php foreach ($data_rows as $order): ?>
        <?php $status_info = $status_map[$order['order_status']] ?? ['text' => 'Đã xóa', 'class' => 'status-deleted']; ?>
        
        <div class="list-card order-card <?php echo ($order['deleted'] == 1) ? 'status-inactive' : ''; ?>">
            <div class="list-card-header">
                <div class="list-card-title">
                    <span class="order-code"><?php echo htmlspecialchars($order['output_code']); ?></span>
                    <span class="sub-text"><?php echo date('d/m/Y H:i', strtotime($order['sell_date'])); ?></span>
                </div>
                <span class="badge <?php echo $status_info['class']; ?>"><?php echo $status_info['text']; ?></span>
            </div>
            
            <div class="list-card-body">
                <div class="list-stat-item">
                    <span class="label">Khách hàng</span>
                    <span class="value"><?php echo htmlspecialchars($order['customer_name']); ?></span>
                </div>
                <div class="list-stat-item">
                    <span class="label">Tổng tiền</span>
                    <span class="value" style="color: var(--text-success); font-weight: bold;"><?php echo number_format($order['total_money']); ?> đ</span>
                </div>
                <?php if ($order['lack'] > 0): ?>
                <div class="list-stat-item">
                    <span class="label">Còn nợ</span>
                    <span class="value" style="color: var(--text-danger); font-weight: bold;"><?php echo number_format($order['lack']); ?> đ</span>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="order-details-content" style="display: none;">
                <div class="loading-spinner"></div>
            </div>

            <div class="order-card-actions">
                <button class="btn-action btn-expand-details" data-id="<?php echo $order['id']; ?>">
                    <i class="fa-solid fa-plus"></i> Chi tiết
                </button>
                <a href="pos_mobile.php?edit_order_id=<?php echo $order['id']; ?>" class="btn-action btn-edit">
                    <i class="fa-solid fa-edit"></i> Sửa
                </a>
                <button class="btn-action btn-delete-order" data-id="<?php echo $order['id']; ?>" data-code="<?php echo $order['output_code']; ?>">
                    <i class="fa-solid fa-trash"></i> Xóa
                </button>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://npmcdn.com/flatpickr/dist/l10n/vn.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const fp_config = { locale: "vn", altInput: true, altFormat: "d/m/Y", dateFormat: "Y-m-d", allowInput: true };
    const fp_from = flatpickr("#filter-from-date", fp_config);
    const fp_to = flatpickr("#filter-to-date", fp_config);

    document.querySelectorAll('.btn-quick-date').forEach(button => {
        button.addEventListener('click', function() {
            const range = this.dataset.range;
            const today = new Date();
            let fromDate;
            
            if (range === 'week') {
                const firstDayOfWeek = today.getDate() - today.getDay() + (today.getDay() === 0 ? -6 : 1);
                fromDate = new Date(today.setDate(firstDayOfWeek));
            } else if (range === 'month') {
                fromDate = new Date(today.getFullYear(), today.getMonth(), 1);
            } else if (range === 'quarter') {
                const currentQuarter = Math.floor(today.getMonth() / 3);
                fromDate = new Date(today.getFullYear(), currentQuarter * 3, 1);
            }
            
            fp_from.setDate(fromDate);
            fp_to.setDate(new Date());
            this.closest('form').submit();
        });
    });

    document.querySelectorAll('.btn-delete-order').forEach(button => {
        button.addEventListener('click', function() {
            const orderId = this.dataset.id;
            const orderCode = this.dataset.code;
            
            if (confirm(`Bạn có chắc chắn muốn XÓA đơn hàng [${orderCode}]?\nThao tác này sẽ hoàn trả tồn kho (nếu có) và không thể hoàn tác!`)) {
                const formData = new FormData();
                formData.append('action', 'delete_order');
                formData.append('order_id', orderId);

                fetch('/quanlybanhang/ajax/orders_ajax.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    if (data.status === 'success') {
                        location.reload(); 
                    }
                })
                .catch(error => alert('Lỗi kết nối. Không thể xóa.'));
            }
        });
    });

    document.querySelectorAll('.btn-expand-details').forEach(button => {
        button.addEventListener('click', function() {
            const btn = this;
            const icon = btn.querySelector('i');
            const orderId = btn.dataset.id;
            const card = btn.closest('.list-card');
            const detailsContainer = card.querySelector('.order-details-content');

            const isShown = detailsContainer.style.display === 'block';

            if (isShown) {
                detailsContainer.style.display = 'none';
                icon.classList.remove('fa-minus');
                icon.classList.add('fa-plus');
                btn.innerHTML = '<i class="fa-solid fa-plus"></i> Chi tiết';
            } else {
                detailsContainer.style.display = 'block';
                icon.classList.remove('fa-plus');
                icon.classList.add('fa-spinner', 'fa-spin');
                btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Đang tải...';

                if (detailsContainer.dataset.loaded === 'true') {
                    icon.classList.remove('fa-spinner', 'fa-spin');
                    icon.classList.add('fa-minus');
                    btn.innerHTML = '<i class="fa-solid fa-minus"></i> Ẩn';
                    return;
                }

                const formData = new FormData();
                formData.append('action', 'get_order_details');
                formData.append('order_id', orderId);

                fetch('/quanlybanhang/ajax/orders_ajax.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    icon.classList.remove('fa-spinner', 'fa-spin');
                    icon.classList.add('fa-minus');
                    btn.innerHTML = '<i class="fa-solid fa-minus"></i> Ẩn';
                    detailsContainer.dataset.loaded = 'true';
                    
                    if (data.status === 'success') {
                        detailsContainer.innerHTML = formatOrderDetails(data.items);
                    } else {
                        detailsContainer.innerHTML = '<p class="error">Lỗi: ' + data.message + '</p>';
                    }
                })
                .catch(error => {
                    detailsContainer.innerHTML = '<p class="error">Lỗi kết nối. Không thể tải chi tiết.</p>';
                    icon.classList.remove('fa-spinner', 'fa-spin');
                    icon.classList.add('fa-plus');
                    btn.innerHTML = '<i class="fa-solid fa-plus"></i> Chi tiết';
                });
            }
        });
    });

    function formatOrderDetails(items) {
        if (!items || items.length === 0) {
            return '<p class="no-items">Đơn hàng không có sản phẩm.</p>';
        }

        let tableHtml = '<table class="details-table"><thead><tr><th>Sản phẩm</th><th>SL</th><th>Đơn giá</th><th>Thành tiền</th></tr></thead><tbody>';
        
        items.forEach(item => {
            let lineTotal = (item.quantity || 0) * (item.price || 0);
            tableHtml += `
                <tr>
                    <td>
                        <span class="item-name">${item.name || 'N/A'}</span>
                        <span class="item-code">${item.code || 'N/A'}</span>
                    </td>
                    <td class="text-center">${item.quantity}</td>
                    <td class="text-right">${Number(item.price).toLocaleString('vi-VN')}</td>
                    <td class="text-right">${Number(lineTotal).toLocaleString('vi-VN')}</td>
                </tr>
            `;
        });
        
        tableHtml += '</tbody></table>';
        return tableHtml;
    }

});
</script>