<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// Handle AJAX queries before doing any HTML
if (isset($_GET['ajax']) || isset($_POST['action'])) {

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

    require_once dirname(__DIR__, 2) . '/include/con_data.php';

    $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 GET list users
    if (isset($_GET['ajax']) && $_GET['ajax'] === 'list') {
        header('Content-Type: application/json');

        $stmt = $pdo->prepare("SELECT id, user_id, name, username, email, role, status, last_login FROM users WHERE shop_id = ? ORDER BY id DESC");
        $stmt->execute([$shop_id]);
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode(['success' => true, 'data' => $users]);
        exit;
    }

    // AJAX POST add user
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
        header('Content-Type: application/json');

        $name = trim($_POST['name'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $role = trim($_POST['role'] ?? 'staff');
        $status = isset($_POST['status']) ? intval($_POST['status']) : 1;

        if (empty($name) || empty($username) || empty($password) || empty($role)) {
            echo json_encode(['success' => false, 'message' => 'ກະລຸນາປ້ອນຂໍ້ມູນໃຫ້ຄົບຖ້ວນ']);
            exit;
        }

        try {
            // Check for duplicate username globally (since login needs to be unique)
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                echo json_encode(['success' => false, 'message' => 'ຊື່ຜູ້ໃຊ້ນີ້ມີໃນລະບົບແລ້ວ']);
                exit;
            }

            // user_id generation relies on a trigger in the DB `trg_users_before_insert`
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (shop_id, name, username, password, email, role, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$shop_id, $name, $username, $hashedPassword, $email, $role, $status]);

            echo json_encode(['success' => true, 'message' => 'ເພີ່ມຜູ້ໃຊ້ສຳເລັດແລ້ວ']);

        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'message' => 'ເກີດຂໍ້ຜິດພາດ: ' . $e->getMessage()]);
        }
        exit;
    }

    // AJAX POST edit user (basic info, not password unless provided)
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit') {
        header('Content-Type: application/json');

        $id = intval($_POST['id']);
        $name = trim($_POST['name'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? ''); // Optional for update
        $email = trim($_POST['email'] ?? '');
        $role = trim($_POST['role'] ?? 'staff');
        $status = isset($_POST['status']) ? intval($_POST['status']) : 1;

        if (empty($id) || empty($name) || empty($username) || empty($role)) {
            echo json_encode(['success' => false, 'message' => 'ກະລຸນາປ້ອນຂໍ້ມູນໃຫ້ຄົບຖ້ວນ']);
            exit;
        }

        try {
            // Check for duplicate username excluding self
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
            $stmt->execute([$username, $id]);
            if ($stmt->fetch()) {
                echo json_encode(['success' => false, 'message' => 'ຊື່ຜູ້ໃຊ້ນີ້ມີໃນລະບົບແລ້ວ']);
                exit;
            }


            if (!empty($password)) {
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET name = ?, username = ?, password = ?, email = ?, role = ?, status = ? WHERE id = ? AND shop_id = ?");
                $stmt->execute([$name, $username, $hashedPassword, $email, $role, $status, $id, $shop_id]);
            } else {
                $stmt = $pdo->prepare("UPDATE users SET name = ?, username = ?, email = ?, role = ?, status = ? WHERE id = ? AND shop_id = ?");
                $stmt->execute([$name, $username, $email, $role, $status, $id, $shop_id]);
            }

            echo json_encode(['success' => true, 'message' => 'ອັບເດດຂໍ້ມູນສຳເລັດແລ້ວ']);

        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'message' => 'ເກີດຂໍ້ຜິດພາດ: ' . $e->getMessage()]);
        }

        exit;
    }
}

// ----- HTML Page Load -----
$page_title = 'ເພີ່ມຜູ້ໃຊ້ເຂົ້າຮ້ານ';
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;
    }

    .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;
    }

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

    .status-badge {
        display: inline-flex;
        align-items: center;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 500;
    }

    .status-active {
        background: rgba(40, 167, 69, 0.1);
        color: #28a745;
        border: 1px solid rgba(40, 167, 69, 0.2);
    }

    .status-inactive {
        background: rgba(220, 53, 69, 0.1);
        color: #dc3545;
        border: 1px solid rgba(220, 53, 69, 0.2);
    }

    /* Modal */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1000;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s;
        backdrop-filter: blur(4px);
    }

    .modal-overlay.show {
        opacity: 1;
        visibility: visible;
    }

    .modal-content {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        width: 90%;
        max-width: 500px;
        transform: translateY(-20px);
        transition: all 0.3s;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    }

    .modal-overlay.show .modal-content {
        transform: translateY(0);
    }

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

    .modal-header h3 {
        margin: 0;
        font-size: 18px;
    }

    .close-modal {
        background: none;
        border: none;
        color: var(--text-secondary);
        font-size: 20px;
        cursor: pointer;
        transition: .2s;
    }

    .close-modal:hover {
        color: var(--danger);
    }

    .modal-body {
        padding: 20px;
    }

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

    .form-group label {
        display: block;
        margin-bottom: 6px;
        color: var(--text-secondary);
        font-size: 14px;
        font-weight: 500;
    }

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

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

    select.form-control {
        appearance: none;
        background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
        background-repeat: no-repeat;
        background-position: right 14px center;
        background-size: 16px;
        padding-right: 40px;
    }

    .modal-footer {
        padding: 15px 20px;
        border-top: 1px solid var(--border-color);
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }
</style>

<div class="content">
    <div class="page-header">
        <h2>
            <div
                style="width: 40px; height: 40px; border-radius: 10px; background: rgba(193,153,42,0.1); color: var(--accent); display: flex; align-items: center; justify-content: center; font-size: 20px;">
                <i class="fa-solid fa-users"></i>
            </div>
            ຈັດການຜູ້ໃຊ້ພາຍໃນຮ້ານ
        </h2>
        <div style="display: flex; gap: 10px;">
            <button class="btn btn-primary" onclick="openModal()">
                <i class="fa-solid fa-plus"></i> ເພີ່ມຜູ້ໃຊ້ໃໝ່
            </button>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div style="overflow-x: auto;">
                <table class="pro-table">
                    <thead>
                        <tr>
                            <th>ລະຫັດຜູ້ໃຊ້</th>
                            <th>ຊື່ ແລະ ນາມສະກຸນ</th>
                            <th>ຊື່ເຂົ້າລະບົບ (Username)</th>
                            <th>ອີເມວ</th>
                            <th>ສິດນຳໃຊ້ (Role)</th>
                            <th>ສະຖານະ</th>
                            <th style="text-align: right;">ຈັດການ</th>
                        </tr>
                    </thead>
                    <tbody id="userTableBody">
                        <tr>
                            <td colspan="7" style="text-align: center; color: var(--text-secondary); padding: 30px;">
                                ກຳລັງໂຫຼດຂໍ້ມູນ...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Modal Form -->
<div class="modal-overlay" id="userModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">ເພີ່ມຜູ້ໃຊ້ໃໝ່</h3>
            <button class="close-modal" onclick="closeModal()">
                <i class="fa-solid fa-xmark"></i>
            </button>
        </div>
        <div class="modal-body">
            <form id="userForm" onsubmit="saveUser(event)">
                <input type="hidden" id="userId" name="id">
                <input type="hidden" id="formAction" name="action" value="add">

                <div class="form-group">
                    <label>ຊື່ ແລະ ນາມສະກຸນ <span style="color: red;">*</span></label>
                    <input type="text" class="form-control" id="name" name="name" required>
                </div>

                <div class="form-group">
                    <label>ຊື່ເຂົ້າລະບົບ (Username) <span style="color: red;">*</span></label>
                    <input type="text" class="form-control" id="username" name="username" required autocomplete="off">
                </div>

                <div class="form-group">
                    <label id="passwordLabel">ລະຫັດຜ່ານ (Password) <span style="color: red;">*</span></label>
                    <input type="password" class="form-control" id="password" name="password" required
                        autocomplete="new-password">
                    <small id="passwordHelp"
                        style="display:none; color: var(--text-secondary); margin-top: 4px;">ປະຫວ່າງໄວ້ຖ້າບໍ່ຕ້ອງການປ່ຽນລະຫັດແຜ່ນໃໝ່</small>
                </div>

                <div class="form-group">
                    <label>ອີເມວ (Email)</label>
                    <input type="email" class="form-control" id="email" name="email">
                </div>

                <div class="form-group">
                    <label>ສິດນຳໃຊ້ (Role) <span style="color: red;">*</span></label>
                    <select class="form-control" id="role" name="role" required>
                        <option value="staff">Staff (ພະນັກງານທົ່ວໄປ)</option>
                        <option value="manager">Manager (ຜູ້ຈັດການ)</option>
                        <option value="representative">Representative (ຕົວແທນ)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>ສະຖານະ</label>
                    <select class="form-control" id="status" name="status">
                        <option value="1">ເປີດນຳໃຊ້ (Active)</option>
                        <option value="0">ປິດນຳໃຊ້ (Inactive)</option>
                    </select>
                </div>

                <div class="modal-footer" style="padding: 15px 0 0 0; margin-top: 15px; border-top: none;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">ຍົກເລີກ</button>
                    <button type="submit" class="btn btn-primary" id="saveBtn">ບັນທຶກ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        loadUsers();
    });

    function loadUsers() {
        const tbody = document.getElementById('userTableBody');
        tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; padding: 30px;"><i class="fa-solid fa-spinner fa-spin"></i> ກຳລັງໂຫຼດເມນູ...</td></tr>';

        fetch('?ajax=list')
            .then(res => res.json())
            .then(res => {
                if (!res.success) {
                    Swal.fire({
                        icon: 'error',
                        title: 'ຜິດພາດ',
                        text: res.message || 'ບໍ່ສາມາດໂຫຼດຂໍ້ມູນໄດ້',
                        background: 'var(--card-bg)',
                        color: 'var(--text-primary)'
                    });
                    tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; padding: 30px;">ບໍ່ມີຂໍ້ມູນ</td></tr>';
                    return;
                }

                if (res.data.length === 0) {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="7" style="text-align: center; padding: 40px; color: var(--text-secondary);">
                                <i class="fa-solid fa-users-slash" style="font-size: 40px; margin-bottom: 10px; opacity: 0.5;"></i>
                                <br>ຍັງບໍ່ມີຜູ້ໃຊ້ໃນລະບົບ
                            </td>
                        </tr>
                    `;
                    return;
                }

                let html = '';
                res.data.forEach(user => {
                    const statusHtml = user.status == 1
                        ? '<span class="status-badge status-active"><i class="fa-solid fa-check-circle" style="margin-right: 5px;"></i> Active</span>'
                        : '<span class="status-badge status-inactive"><i class="fa-solid fa-times-circle" style="margin-right: 5px;"></i> Inactive</span>';

                    // Note: Role translation
                    let roleStr = user.role;
                    if (roleStr === 'manager') roleStr = 'Manager';
                    else if (roleStr === 'superadmin') roleStr = 'Superadmin';
                    else if (roleStr === 'staff') roleStr = 'Staff';
                    else if (roleStr === 'representative') roleStr = 'Representative';

                    html += `
                        <tr>
                            <td><span class="badge-code">${user.user_id || '-'}</span></td>
                            <td style="font-weight: 500;">${user.name}</td>
                            <td>${user.username}</td>
                            <td>${user.email || '-'}</td>
                            <td>${roleStr}</td>
                            <td>${statusHtml}</td>
                            <td style="text-align: right;">
                                <div style="display: flex; gap: 5px; justify-content: flex-end;">
                                    <button class="btn-icon edit" onclick='editUser(${JSON.stringify(user).replace(/'/g, "&apos;")})' title="ແກ້ໄຂ">
                                        <i class="fa-solid fa-pen"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
                });
                tbody.innerHTML = html;
            })
            .catch(err => {
                console.error(err);
                tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: var(--danger); padding: 30px;">ເກີດຂໍ້ຜິດພາດໃນການເຊື່ອມຕໍ່</td></tr>';
            });
    }

    function openModal() {
        document.getElementById('formAction').value = 'add';
        document.getElementById('userId').value = '';
        document.getElementById('modalTitle').textContent = 'ເພີ່ມຜູ້ໃຊ້ໃໝ່';
        document.getElementById('userForm').reset();

        // Require password for new users
        document.getElementById('password').required = true;
        document.getElementById('passwordLabel').innerHTML = 'ລະຫັດຜ່ານ (Password) <span style="color: red;">*</span>';
        document.getElementById('passwordHelp').style.display = 'none';

        document.getElementById('userModal').classList.add('show');
    }

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

    function editUser(user) {
        document.getElementById('formAction').value = 'edit';
        document.getElementById('userId').value = user.id;
        document.getElementById('modalTitle').textContent = 'ແກ້ໄຂຜູ້ໃຊ້';

        document.getElementById('name').value = user.name;
        document.getElementById('username').value = user.username;
        document.getElementById('email').value = user.email || '';
        document.getElementById('role').value = user.role;
        document.getElementById('status').value = user.status;

        // Password not required for updates, allow leaving empty to keep current
        document.getElementById('password').value = '';
        document.getElementById('password').required = false;
        document.getElementById('passwordLabel').innerHTML = 'ລະຫັດຜ່ານໃໝ່ (ປ່ຽນໃໝ່)';
        document.getElementById('passwordHelp').style.display = 'block';

        document.getElementById('userModal').classList.add('show');
    }

    function saveUser(e) {
        e.preventDefault();
        const btn = document.getElementById('saveBtn');
        const ogText = btn.innerHTML;
        btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> ກຳລັງບັນທຶກ...';
        btn.disabled = true;

        const formData = new FormData(e.target);

        fetch('add_user.php', {
            method: 'POST',
            body: formData
        })
            .then(res => res.json())
            .then(res => {
                btn.innerHTML = ogText;
                btn.disabled = false;

                if (res.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'ສຳເລັດ',
                        text: res.message,
                        timer: 1500,
                        showConfirmButton: false,
                        background: 'var(--card-bg)',
                        color: 'var(--text-primary)'
                    });
                    closeModal();
                    loadUsers();
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'ຜິດພາດ',
                        text: res.message,
                        background: 'var(--card-bg)',
                        color: 'var(--text-primary)'
                    });
                }
            })
            .catch(err => {
                console.error(err);
                btn.innerHTML = ogText;
                btn.disabled = false;
                Swal.fire({
                    icon: 'error',
                    title: 'ຜິດພາດ',
                    text: 'ບໍ່ສາມາດບັນທຶກຂໍ້ມູນໄດ້',
                    background: 'var(--card-bg)',
                    color: 'var(--text-primary)'
                });
            });
    }
</script>

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