<?php
/* ==========================================================================
   PHẦN 1: XỬ LÝ LOGIC
   ========================================================================== */
session_start();

require_once __DIR__ . '/../../templates/header.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/helpers.php';

$users = $conn->query("SELECT id, username FROM cms_users WHERE user_status = 1 ORDER BY username ASC")->fetch_all(MYSQLI_ASSOC);
$stores = $conn->query("SELECT id, store_name FROM cms_stores ORDER BY store_name ASC")->fetch_all(MYSQLI_ASSOC);

$filter_from_date = $_GET['from_date'] ?? '';
$filter_to_date = $_GET['to_date'] ?? '';
$filter_user_id_get = $_GET['user_id'] ?? '';

$sql = "SELECT
            ps.ID, ps.output_code, ps.created, ps.date_order, ps.total_quantity, ps.total_money,
            ps.detail_order_id, u.username, s.store_name
        FROM cms_output ps
        JOIN cms_users u ON ps.user_init = u.id
        LEFT JOIN cms_stores s ON ps.store_id = s.id";

$where_clauses = [];
$params = [];
$types = '';

if ($filter_user_id_get !== '' && is_numeric($filter_user_id_get)) {
    $filter_user_id = intval($filter_user_id_get);
    $where_clauses[] = "ps.user_init = ?";
    $params[] = &$filter_user_id;
    $types .= 'i';
} else {
    $filter_user_id = '';
}

if (!empty($filter_from_date)) {
    $where_clauses[] = "DATE(ps.created) >= ?";
    $params[] = &$filter_from_date;
    $types .= 's';
}
if (!empty($filter_to_date)) {
    $where_clauses[] = "DATE(ps.created) <= ?";
    $params[] = &$filter_to_date;
    $types .= 's';
}

if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(' AND ', $where_clauses);
}

$sql .= " ORDER BY ps.id DESC";

$stmt = $conn->prepare($sql);
if ($stmt === false) { die("Lỗi prepare SQL: " . $conn->error); }

if (!empty($types)) {
    call_user_func_array([$stmt, 'bind_param'], array_merge([$types], $params));
}

$stmt->execute();
$all_picking_slips = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

/* ==========================================================================
   PHẦN 2: HIỂN THỊ GIAO DIỆN
   ========================================================================== */
?>

<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">Danh sách phiếu soạn hàng</h1>

    <?php
    if (isset($_SESSION['flash_message'])) {
        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">' . $_SESSION['flash_message'] . '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';
        unset($_SESSION['flash_message']);
    }
    if (isset($_SESSION['flash_message_error'])) {
        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">' . $_SESSION['flash_message_error'] . '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';
        unset($_SESSION['flash_message_error']);
    }
    ?>

    <div class="card shadow mb-4">
        <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Lọc và Tạo phiếu</h6></div>
        <div class="card-body">
            <form action="create_picking_slip.php" method="POST" class="mb-4 border-bottom pb-4">
                <h6 class="mb-3">Tạo phiếu mới</h6>
                <div class="row align-items-end">
                    <div class="col-md-3"><label>Chọn nhân viên bán hàng:</label><select name="user_id" class="form-control" required><option value="">-- Chọn nhân viên --</option><?php foreach($users as $user): ?><option value="<?php echo $user['id']; ?>"><?php echo htmlspecialchars($user['username']); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-3"><label>Tại kho:</label><select name="store_id" class="form-control" required><option value="">-- Chọn kho --</option><?php foreach($stores as $store): ?><option value="<?php echo $store['id']; ?>"><?php echo htmlspecialchars($store['store_name']); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-3"><label>Ngày của các đơn hàng:</label><input type="date" name="date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required></div>
                    <div class="col-md-3"><button type="submit" class="btn btn-primary"><i class="fas fa-plus-circle"></i> Tạo phiếu soạn hàng</button></div>
                </div>
            </form>

            <form method="GET" class="mt-4">
                <h6 class="mb-3">Tìm kiếm phiếu đã tạo</h6>
                <div class="row align-items-end">
                    <div class="col-md-3"><label>Nhân viên:</label><select name="user_id" class="form-control"><option value="">-- Tất cả --</option><?php foreach($users as $user): ?><option value="<?php echo $user['id']; ?>" <?php echo ($filter_user_id_get !== '' && $filter_user_id_get == $user['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($user['username']); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-3"><label>Từ ngày:</label><input type="date" name="from_date" class="form-control" value="<?php echo htmlspecialchars($filter_from_date); ?>"></div>
                    <div class="col-md-3"><label>Đến ngày:</label><input type="date" name="to_date" class="form-control" value="<?php echo htmlspecialchars($filter_to_date); ?>"></div>
                    <div class="col-md-3"><button type="submit" class="btn btn-info btn-block"><i class="fas fa-search"></i> Tìm kiếm</button></div>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Kết quả</h6></div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th class="text-center">STT</th>
                            <th>Mã phiếu</th>
                            <th>Kho xuất</th>
                            <th>Ngày tạo</th>
                            <th>Ngày bán</th>
                            <th>Nhân viên tạo</th>
                            <th class="text-right">Tổng SL</th>
                            <th class="text-right">Tổng tiền</th>
                            <th class="text-center">Hành động</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($all_picking_slips)): ?>
                            <tr><td colspan="9" class="text-center">Không tìm thấy phiếu soạn hàng nào.</td></tr>
                        <?php else: ?>
                            <?php $stt = 1; foreach($all_picking_slips as $slip): ?>
                            <tr>
                                <td class="text-center"><?php echo $stt++; ?></td>
                                <td><?php echo htmlspecialchars($slip['output_code'] ?? 'N/A'); ?></td>
                                <td><?php echo htmlspecialchars($slip['store_name'] ?? 'N/A'); ?></td>
                                <td><?php echo date('H:i d/m/Y', strtotime($slip['created'])); ?></td>
                                <td><?php echo (!empty($slip['date_order']) && $slip['date_order'] !== '0000-00-00') ? date('d/m/Y', strtotime($slip['date_order'])) : 'N/A'; ?></td>
                                <td><?php echo htmlspecialchars($slip['username']); ?></td>
                                <td class="text-right"><?php echo number_format($slip['total_quantity'] ?? 0); ?></td>
                                <td class="text-right"><?php echo number_format($slip['total_money'] ?? 0); ?></td>
                                <td class="text-center">
                                    <a href="print_picking_slip.php?id=<?php echo $slip['ID']; ?>" class="btn btn-info btn-sm" target="_blank" title="In phiếu"><i class="fas fa-print"></i></a>
                                    <a href="export_delivery_list.php?id=<?php echo $slip['ID']; ?>" class="btn btn-success btn-sm" title="Xuất Excel danh sách giao hàng"><i class="fas fa-file-excel"></i></a>
                                    <a href="delete_picking_slip.php?id=<?php echo $slip['ID']; ?>" class="btn btn-danger btn-sm" title="Xóa phiếu" onclick="return confirm('Bạn có chắc chắn muốn xóa phiếu <?php echo htmlspecialchars($slip['output_code'] ?? 'này'); ?>?');"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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

<script>
    $(document).ready(function() {
        $('#dataTable').DataTable({
            "order": [],
            "columnDefs": [ { "orderable": false, "targets": 8 } ],
            "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" }
        });
    });
</script>