<?php
// Handle AJAX requests BEFORE any HTML output
if (isset($_POST['action']) || isset($_GET['ajax'])) {
    if (session_status() === PHP_SESSION_NONE)
        session_start();
    require_once dirname(__DIR__, 2) . '/include/con_data.php';

    // Check auth
    if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['manager', 'staff'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        exit;
    }

    // Multi-store: get shop_id
    $shop_id = $_SESSION['shop_id'] ?? null;
    if (!$shop_id) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'No shop assigned']);
        exit;
    }

    // AJAX: Fetch paginated brands
    if (isset($_GET['ajax']) && $_GET['ajax'] === 'list') {
        header('Content-Type: application/json');

        $page = max(1, intval($_GET['page'] ?? 1));
        $limit = 15;
        $offset = ($page - 1) * $limit;
        $search = trim($_GET['search'] ?? '');

        // Build WHERE clause
        $where = "b.shop_id = :shop_id";
        $params = [':shop_id' => $shop_id];

        if ($search !== '') {
            $where .= " AND (brand_name LIKE :s)";
            $params[':s'] = "%$search%";
        }

        // Use SQL_CALC_FOUND_ROWS to get total in one pass
        // Also get usage count to disable delete button if used
        $sql = "SELECT SQL_CALC_FOUND_ROWS b.BR_id as id, b.brand_name as name,
                (SELECT COUNT(*) FROM products p WHERE p.brand = b.BR_id AND p.deleted_at IS NULL AND p.shop_id = :shop_id2) as use_count
                FROM brand b WHERE $where ORDER BY b.id ASC LIMIT $limit OFFSET $offset";
        $params[':shop_id2'] = $shop_id;
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $total = intval($pdo->query("SELECT FOUND_ROWS()")->fetchColumn());

        echo json_encode([
            'success' => true,
            'data' => $rows,
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'totalPages' => ceil($total / $limit)
        ]);
        exit;
    }

    // AJAX: Add / Edit / Delete
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        header('Content-Type: application/json');
        $action = $_POST['action'];
        $username = $_SESSION['username'] ?? 'System';

        try {
            if ($action === 'add') {
                $name = trim($_POST['brand_name'] ?? '');
                if (!$name) {
                    echo json_encode(['success' => false, 'message' => 'Name required']);
                    exit;
                }

                $stmt = $pdo->prepare("INSERT INTO brand (brand_name, shop_id) VALUES (:name, :shop_id)");
                $stmt->execute([':name' => $name, ':shop_id' => $shop_id]);
                echo json_encode(['success' => true, 'message' => 'ເພີ່ມ Brand ສິນຄ້າສຳເລັດ']);
                exit;
            }

            if ($action === 'edit') {
                $id = $_POST['id'];
                $name = trim($_POST['brand_name'] ?? '');
                if (!$name) {
                    echo json_encode(['success' => false, 'message' => 'Name required']);
                    exit;
                }

                $stmt = $pdo->prepare("UPDATE brand SET brand_name = :name WHERE BR_id = :id AND shop_id = :shop_id");
                $stmt->execute([':name' => $name, ':id' => $id, ':shop_id' => $shop_id]);
                echo json_encode(['success' => true, 'message' => 'ແກ້ໄຂ Brand ສິນຄ້າສຳເລັດ']);
                exit;
            }

            if ($action === 'delete') {
                // Check if used in products (optional, but good practice)
                $count = $pdo->prepare("SELECT COUNT(*) FROM products WHERE brand = :id AND deleted_at IS NULL AND shop_id = :shop_id");
                $count->execute([':id' => $_POST['id'], ':shop_id' => $shop_id]);
                if ($count->fetchColumn() > 0) {
                    echo json_encode(['success' => false, 'message' => 'ບໍ່ສາມາດລຶບໄດ້ ເນື່ອງຈາກມີການໃຊ້ງານຢູ່ໃນສິນຄ້າ']);
                    exit;
                }

                $stmt = $pdo->prepare("DELETE FROM brand WHERE BR_id = :id AND shop_id = :shop_id");
                $stmt->execute([':id' => $_POST['id'], ':shop_id' => $shop_id]);
                echo json_encode(['success' => true, 'message' => 'ລຶບ Brand ສິນຄ້າສຳເລັດ']);
                exit;
            }
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
            exit;
        }
    }
}

// ===== Regular Page Load (HTML only, NO data fetch at all) =====
$page_title = 'ຈັດການຂໍ້ມູນ';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
$user_role = $_SESSION['role'] ?? '';
require_once '../includes/header.php';
?>

<style>
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        flex-wrap: wrap;
        gap: 12px;
    }

    .page-header h2 {
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .search-wrap {
        display: flex;
        align-items: center;
        gap: 10px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        padding: 8px 14px;
        width: 350px;
        max-width: 100%;
    }

    .search-wrap input {
        border: none;
        background: transparent;
        outline: none;
        color: var(--text-primary);
        width: 100%;
        font-size: 14px;
        font-family: inherit;
    }

    .search-wrap input::placeholder {
        color: var(--text-secondary);
    }

    .pro-table {
        width: 100%;
        border-collapse: collapse;
    }

    .pro-table th {
        background: rgba(193, 153, 42, 0.1);
        padding: 12px 14px;
        font-weight: 600;
        font-size: 13px;
        text-transform: uppercase;
        color: var(--text-secondary);
        white-space: nowrap;
        text-align: left;
    }

    .pro-table td {
        padding: 14px;
        border-bottom: 1px solid var(--border-color);
        vertical-align: middle;
        color: var(--text-primary);
    }

    .pro-table tbody tr:hover {
        background: rgba(193, 153, 42, 0.03);
    }

    .action-btns {
        display: flex;
        gap: 6px;
    }

    .btn-icon {
        width: 34px;
        height: 34px;
        border-radius: 8px;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all .2s;
        font-size: 13px;
    }

    .btn-icon.edit {
        background: rgba(255, 193, 7, .15);
        color: #ffc107;
    }

    .btn-icon.edit:hover {
        background: #ffc107;
        color: #000;
    }

    .btn-icon.delete {
        background: rgba(220, 53, 69, .15);
        color: #dc3545;
    }

    .btn-icon.delete:hover {
        background: #dc3545;
        color: #fff;
    }

    .empty-state {
        text-align: center;
        padding: 50px 20px;
        color: var(--text-secondary);
    }

    .empty-state i {
        font-size: 48px;
        opacity: .3;
        margin-bottom: 15px;
        display: block;
    }

    .loading-state {
        text-align: center;
        padding: 40px;
        color: var(--text-secondary);
    }

    /* Pagination */
    .pagination-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        border-top: 1px solid var(--border-color);
        flex-wrap: wrap;
        gap: 10px;
    }

    .pagination-info {
        font-size: 14px;
        color: var(--text-secondary);
    }

    .pagination-btns {
        display: flex;
        gap: 4px;
    }

    .pagination-btns button {
        min-width: 36px;
        height: 36px;
        border: 1px solid var(--border-color);
        background: var(--card-bg);
        color: var(--text-primary);
        border-radius: 8px;
        cursor: pointer;
        font-size: 13px;
        transition: all .2s;
        font-family: inherit;
    }

    .pagination-btns button:hover {
        border-color: var(--accent);
        color: var(--accent);
    }

    .pagination-btns button.active {
        background: var(--accent);
        color: #fff;
        border-color: var(--accent);
    }

    .pagination-btns button:disabled {
        opacity: .4;
        cursor: not-allowed;
    }

    /* Modal */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, .7);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 1000;
        backdrop-filter: blur(4px);
    }

    .modal-overlay.show {
        display: flex;
        animation: fadeIn .25s ease;
    }

    .modal-container {
        background: var(--bg-primary);
        width: 100%;
        max-width: 500px;
        border-radius: 15px;
        border: 1px solid var(--border-color);
        box-shadow: 0 15px 40px rgba(0, 0, 0, .4);
        max-height: 90vh;
        overflow-y: auto;
        animation: slideUp .3s ease;
    }

    .modal-header {
        padding: 18px 20px;
        border-bottom: 1px solid var(--border-color);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .modal-header h3 {
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 18px;
    }

    .modal-header h3 i {
        color: var(--accent);
    }

    .modal-body {
        padding: 20px;
    }

    .modal-footer {
        padding: 15px 20px;
        border-top: 1px solid var(--border-color);
        text-align: right;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    .close-btn {
        background: none;
        border: none;
        color: var(--text-secondary);
        font-size: 22px;
        cursor: pointer;
        width: 34px;
        height: 34px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .close-btn:hover {
        background: rgba(220, 53, 69, .1);
        color: var(--danger);
    }

    .form-group {
        margin-bottom: 16px;
    }

    .form-group label {
        display: block;
        margin-bottom: 6px;
        font-weight: 500;
        font-size: 14px;
    }

    .form-control {
        width: 100%;
        padding: 10px 14px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        color: var(--text-primary);
        font-family: inherit;
        font-size: 14px;
        transition: border-color .2s;
    }

    .form-control:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 2px rgba(193, 153, 42, .15);
    }

    .text-danger {
        color: var(--danger);
    }

    @keyframes fadeIn {
        from {
            opacity: 0
        }

        to {
            opacity: 1
        }
    }

    @keyframes slideUp {
        from {
            opacity: 0;
            transform: translateY(20px)
        }

        to {
            opacity: 1;
            transform: translateY(0)
        }
    }

    /* Mobile Responsive */
    @media(max-width:768px) {
        .page-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .search-wrap {
            width: 100%;
        }

        .pro-table thead {
            display: none;
        }

        /* Card Style */
        .pro-table tr {
            display: block;
            border: 1px solid var(--border-color);
            margin-bottom: 12px;
            background: var(--card-bg);
            border-radius: 12px;
            padding: 15px;
            position: relative;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }

        .pro-table td {
            display: block;
            width: 100%;
            padding: 0;
            border: none;
        }

        /* Order # - Hide */
        .pro-table td[data-label="#"] {
            display: none;
        }

        /* Brand Name - Main Title */
        .pro-table td[data-label="ຊື່ Brand"] {
            font-size: 16px;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 5px;
            padding-right: 80px;
            /* Space for actions */
        }

        .pro-table td[data-label="ຊື່ Brand"]::before {
            display: none;
        }

        /* Actions - Top Right Absolute */
        .pro-table td[data-label="ຈັດການ"] {
            position: absolute;
            top: 15px;
            right: 15px;
            width: auto;
        }

        .pro-table td[data-label="ຈັດການ"]::before {
            display: none;
        }

        .action-btns {
            justify-content: flex-end;
            gap: 8px;
        }

        /* Larger touch targets for mobile */
        .btn-icon {
            width: 38px;
            height: 38px;
            font-size: 14px;
        }
    }
</style>

<!-- Page Header -->
<div class="page-header">
    <h2><i class="fas fa-certificate" style="color:var(--accent)"></i> ຈັດການ Brand ສິນຄ້າ</h2>
    <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
        <div class="search-wrap">
            <i class="fas fa-search" style="color:var(--text-secondary)"></i>
            <input type="text" id="searchInput" placeholder="ຄົ້ນຫາຊື່ Brand..." oninput="debounceSearch()">
        </div>
        <button class="btn btn-primary" onclick="openModal('add')"
            style="padding: 10px 20px; background: var(--primary); color: #fff; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px;">
            <i class="fas fa-plus-circle"></i> ເພີ່ມ Brand
        </button>
    </div>
</div>

<!-- Data Card -->
<div class="card"
    style="background: var(--card-bg); border-radius: 12px; border: 1px solid var(--border-color); overflow: hidden;">
    <div style="overflow-x:auto;">
        <table class="pro-table">
            <thead>
                <tr>
                    <th width="80">#</th>
                    <th>ຊື່ Brand</th>
                    <th width="150" style="text-align:center">ຈັດການ</th>
                </tr>
            </thead>
            <tbody id="tableBody">
                <tr>
                    <td colspan="3" class="loading-state"><i class="fas fa-spinner fa-spin"></i> ກຳລັງໂຫຼດຂໍ້ມູນ...</td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <div class="pagination-wrap" id="pagination"></div>
</div>

<!-- Add/Edit Modal -->
<div class="modal-overlay" id="brandModal">
    <div class="modal-container">
        <div class="modal-header">
            <h3 id="modalTitle"><i class="fas fa-plus-circle"></i> ເພີ່ມ Brand</h3>
            <button class="close-btn" onclick="closeModal()">&times;</button>
        </div>
        <form id="brandForm" onsubmit="saveBrand(event)">
            <input type="hidden" id="brandId" name="id">
            <input type="hidden" id="formAction" name="action" value="add">

            <div class="modal-body">
                <div class="form-group">
                    <label>ຊື່ Brand <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="brand_name" name="brand_name" required
                        placeholder="ໃສ່ຊື່ Brand">
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn"
                    style="background:var(--bg-secondary);color:var(--text-primary);padding:10px 20px;border-radius:8px;border:1px solid var(--border-color);cursor:pointer;"
                    onclick="closeModal()">ຍົກເລີກ</button>
                <button type="submit" class="btn"
                    style="background:var(--primary);color:#fff;padding:10px 20px;border-radius:8px;border:none;cursor:pointer;"><i
                        class="fas fa-save"></i> ບັນທຶກ</button>
            </div>
        </form>
    </div>
</div>

<script>
    let currentPage = 1;
    let currentSearch = '';
    let searchTimer = null;

    document.addEventListener('DOMContentLoaded', () => {
        fetchData();
    });

    function debounceSearch() {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => {
            currentSearch = document.getElementById('searchInput').value;
            currentPage = 1;
            fetchData();
        }, 300);
    }

    function fetchData() {
        const tbody = document.getElementById('tableBody');
        tbody.innerHTML = '<tr><td colspan="3" class="loading-state"><i class="fas fa-spinner fa-spin"></i> ກຳລັງໂຫຼດຂໍ້ມູນ...</td></tr>';

        const params = new URLSearchParams({
            ajax: 'list',
            page: currentPage,
            search: currentSearch
        });

        fetch('make_brand.php?' + params.toString())
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    renderTable(res.data, res.page, res.limit);
                    renderPagination(res.page, res.totalPages, res.total);
                } else {
                    tbody.innerHTML = `<tr><td colspan="3" class="empty-state"><i class="fas fa-exclamation-triangle"></i> ${res.message || 'Error loading data'}</td></tr>`;
                }
            })
            .catch(err => {
                console.error(err);
                tbody.innerHTML = '<tr><td colspan="3" class="empty-state"><i class="fas fa-exclamation-triangle"></i> Error loading data</td></tr>';
            });
    }

    function renderTable(data, page, limit) {
        const tbody = document.getElementById('tableBody');

        if (data.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="3" class="empty-state">
                        <i class="fas fa-certificate"></i>
                        <p>ບໍ່ພົບຂໍ້ມູນ Brand</p>
                    </td>
                </tr>`;
            return;
        }

        let html = '';
        data.forEach((item, index) => {
            const order = ((page - 1) * limit) + (index + 1);
            html += `
                <tr>
                    <td data-label="#">${order}</td>
                    <td data-label="ຊື່ Brand" style="font-weight:500;font-size:15px;">${item.name}</td>
                    <td data-label="ຈັດການ" style="text-align:center">
                        <div class="action-btns" style="justify-content:center;">
                            <button class="btn-icon edit" onclick='openModal("edit", ${JSON.stringify(item)})' title="ແກ້ໄຂ">
                                <i class="fas fa-edit"></i>
                            </button>
                            <?php if ($user_role !== 'staff'): ?>
                            <button class="btn-icon delete" onclick="deleteBrand('${item.id}', ${item.use_count})" title="ລຶບ">
                                <i class="fas fa-trash"></i>
                            </button>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            `;
        });
        tbody.innerHTML = html;
    }

    function renderPagination(current, totalPages, totalItems) {
        const container = document.getElementById('pagination');
        if (totalPages <= 1) {
            container.innerHTML = `<div class="pagination-info">ທັງໝົດ ${totalItems} ລາຍການ</div>`;
            return;
        }

        let buttons = '';
        // Previous
        buttons += `<button onclick="changePage(${current - 1})" ${current === 1 ? 'disabled' : ''}><i class="fas fa-chevron-left"></i></button>`;

        // Page numbers
        for (let i = 1; i <= totalPages; i++) {
            if (i === 1 || i === totalPages || (i >= current - 2 && i <= current + 2)) {
                buttons += `<button onclick="changePage(${i})" class="${i === current ? 'active' : ''}">${i}</button>`;
            } else if (i === current - 3 || i === current + 3) {
                buttons += `<button disabled>...</button>`;
            }
        }

        // Next
        buttons += `<button onclick="changePage(${current + 1})" ${current === totalPages ? 'disabled' : ''}><i class="fas fa-chevron-right"></i></button>`;

        container.innerHTML = `
            <div class="pagination-info">ສະແດງໜ້າ ${current} ຈາກ ${totalPages} (ທັງໝົດ ${totalItems} ລາຍການ)</div>
            <div class="pagination-btns">${buttons}</div>
        `;
    }

    function changePage(page) {
        if (page < 1) return;
        currentPage = page;
        fetchData();
    }

    // Modal Functions
    function openModal(mode, data = null) {
        const modal = document.getElementById('brandModal');
        const form = document.getElementById('brandForm');
        const title = document.getElementById('modalTitle');
        const btn = form.querySelector('button[type="submit"]');

        if (mode === 'add') {
            title.innerHTML = '<i class="fas fa-plus-circle"></i> ເພີ່ມ Brand';
            document.getElementById('formAction').value = 'add';
            document.getElementById('brandId').value = '';
            document.getElementById('brand_name').value = '';
            btn.innerHTML = '<i class="fas fa-save"></i> ບັນທຶກ';
        } else {
            title.innerHTML = '<i class="fas fa-edit"></i> ແກ້ໄຂ Brand';
            document.getElementById('formAction').value = 'edit';
            document.getElementById('brandId').value = data.id;
            document.getElementById('brand_name').value = data.name;
            btn.innerHTML = '<i class="fas fa-save"></i> ອັບເດດ';
        }

        modal.classList.add('show');
    }

    function closeModal() {
        document.getElementById('brandModal').classList.remove('show');
    }

    function saveBrand(e) {
        e.preventDefault();
        const output = document.getElementById('brandForm').querySelector('button[type="submit"]');
        const oldText = output.innerHTML;
        output.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ກຳລັງບັນທຶກ...';
        output.disabled = true;

        const formData = new FormData(e.target);

        fetch('make_brand.php', {
            method: 'POST',
            body: formData
        })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'ສຳເລັດ!',
                        text: res.message,
                        timer: 1500,
                        showConfirmButton: false
                    });
                    closeModal();
                    fetchData();
                } else {
                    Swal.fire('ຜິດພາດ!', res.message, 'error');
                }
            })
            .catch(err => {
                console.error(err);
                Swal.fire('ຜິດພາດ!', 'Server Error', 'error');
            })
            .finally(() => {
                output.innerHTML = oldText;
                output.disabled = false;
            });
    }

    function deleteBrand(id, useCount) {
        if (useCount > 0) {
            Swal.fire({
                icon: 'error',
                title: 'ບໍ່ສາມາດລຶບໄດ້!',
                text: `Brand ນີ້ກຳລັງຖືກໃຊ້ງານຢູ່ ${useCount} ລາຍການ`,
                confirmButtonText: 'ຕົກລົງ'
            });
            return;
        }

        Swal.fire({
            title: 'ຢືນຢັນການລຶບ?',
            text: "ທ່ານຕ້ອງການລຶບ Brand ນີ້ແທ້ບໍ່?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'ລຶບ',
            cancelButtonText: 'ຍົກເລີກ'
        }).then((result) => {
            if (result.isConfirmed) {
                const fd = new FormData();
                fd.append('action', 'delete');
                fd.append('id', id);

                fetch('make_brand.php', { method: 'POST', body: fd })
                    .then(r => r.json())
                    .then(res => {
                        if (res.success) {
                            Swal.fire('ລຶບສຳເລັດ!', res.message, 'success');
                            fetchData();
                        } else {
                            Swal.fire('ຜິດພາດ!', res.message, 'error');
                        }
                    })
                    .catch(err => Swal.fire('Error', 'Server Error', 'error'));
            }
        });
    }

    // Close modal on outside click
    document.getElementById('brandModal').addEventListener('click', (e) => {
        if (e.target === document.getElementById('brandModal')) closeModal();
    });
</script>

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