<?php
require_once __DIR__ . '/../../templates/header.php';

$errors = [];
$is_edit_mode = isset($_GET['id']) && is_numeric($_GET['id']);
$product_id = $is_edit_mode ? intval($_GET['id']) : 0;
$product_data = [];

if ($is_edit_mode) {
    $stmt_fetch = $conn->prepare("SELECT * FROM cms_products WHERE id = ? AND deleted = 0");
    if ($stmt_fetch) {
        $stmt_fetch->bind_param("i", $product_id);
        $stmt_fetch->execute();
        $result = $stmt_fetch->get_result();
        $product_data = $result->fetch_assoc();
        $stmt_fetch->close();
        if (!$product_data) {
            die('Sản phẩm không tồn tại hoặc đã bị xóa.');
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $prd_id_post        = intval($_POST['prd_id'] ?? 0);
    $prd_name           = trim($_POST['prd_name'] ?? '');
    $prd_code           = trim($_POST['prd_code'] ?? '');
    $prd_origin_price   = intval(str_replace(',', '', $_POST['prd_origin_price'] ?? 0));
    $prd_sell_price     = intval(str_replace(',', '', $_POST['prd_sell_price'] ?? 0));
    $prd_sell_price2    = intval(str_replace(',', '', $_POST['prd_sell_price2'] ?? 0));
    $prd_manufacture_id = intval($_POST['prd_manufacture_id'] ?? 0);
    $prd_group_id       = intval($_POST['prd_group_id'] ?? 0);
    $prd_unit_id        = intval($_POST['prd_unit_id'] ?? 0);
    $prd_tenquycach     = trim($_POST['prd_tenquycach'] ?? '');
    $prd_quycach        = intval($_POST['prd_quycach'] ?? 0);

    if (empty($prd_name)) {
        $errors[] = 'Tên sản phẩm không được để trống.';
    }
    if ($prd_sell_price <= 0) {
        $errors[] = 'Giá bán lẻ phải là một số lớn hơn 0.';
    }

    if (empty($errors)) {
        $check_sql = "SELECT id FROM cms_products WHERE (prd_name = ? OR (prd_code != '' AND prd_code = ?)) AND id != ?";
        $stmt_check = $conn->prepare($check_sql);
        $stmt_check->bind_param("ssi", $prd_name, $prd_code, $prd_id_post);
        $stmt_check->execute();
        if ($stmt_check->get_result()->num_rows > 0) {
            $errors[] = "Tên hoặc Mã sản phẩm đã tồn tại trong hệ thống.";
        }
        $stmt_check->close();
    }
    
    if (empty($errors)) {
        if ($prd_id_post > 0) {
            $sql = "UPDATE cms_products 
                    SET prd_name=?, prd_code=?, prd_origin_price=?, prd_sell_price=?, prd_sell_price2=?, 
                        prd_unit_id=?, prd_group_id=?, prd_manufacture_id=?, prd_quycach=?, prd_tenquycach=?, updated=NOW() 
                    WHERE id=?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssiiiiiisis", 
                $prd_name, $prd_code, $prd_origin_price, $prd_sell_price, $prd_sell_price2, 
                $prd_unit_id, $prd_group_id, $prd_manufacture_id, $prd_quycach, $prd_tenquycach, 
                $prd_id_post
            );
        } else {
            if (empty($prd_code)) {
                $prd_code = 'SP' . time();
            }
            $sql = "INSERT INTO cms_products 
                        (prd_name, prd_code, prd_origin_price, prd_sell_price, prd_sell_price2, 
                         prd_unit_id, prd_group_id, prd_manufacture_id, prd_quycach, prd_tenquycach, 
                         created, updated) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssiiiiiisi", 
                $prd_name, $prd_code, $prd_origin_price, $prd_sell_price, $prd_sell_price2, 
                $prd_unit_id, $prd_group_id, $prd_manufacture_id, $prd_quycach, $prd_tenquycach
            );
        }

        if ($stmt->execute()) {
            $success_msg = $is_edit_mode ? "Cập nhật sản phẩm thành công!" : "Thêm mới sản phẩm thành công!";
            echo "<script>alert('{$success_msg}'); window.location.href = '/quanlybanhang/modules/products/list.php';</script>";
            exit;
        } else {
            $errors[] = "Lỗi khi lưu vào cơ sở dữ liệu: " . $stmt->error;
        }
        $stmt->close();
    }
}

$categories_list = $conn->query("SELECT id, prd_group_name FROM cms_products_group ORDER BY prd_group_name ASC")->fetch_all(MYSQLI_ASSOC);
$manufacturers_list = $conn->query("SELECT id, prd_manuf_name FROM cms_products_manufacture ORDER BY prd_manuf_name ASC")->fetch_all(MYSQLI_ASSOC);
$units_list = $conn->query("SELECT id, prd_unit_name FROM cms_products_unit ORDER BY prd_unit_name ASC")->fetch_all(MYSQLI_ASSOC);

$display_data = !empty($errors) ? $_POST : ($is_edit_mode ? $product_data : []);
?>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css">

<style>
    .form-section {
        border: 1px solid #e3e6f0;
        border-radius: .35rem;
        padding: 1.5rem;
        margin-bottom: 2rem;
        background-color: #fff;
    }
    .form-section h5 {
        font-size: 1.1rem;
        font-weight: 700;
        color: #4e73df;
        margin-bottom: 1.25rem;
        padding-bottom: 0.5rem;
        border-bottom: 1px solid #e3e6f0;
    }
    .form-group {
        margin-bottom: 1.25rem;
    }
    .select2-container {
        width: 85% !important;
        flex-grow: 1;
    }
    .select2-container--bootstrap4 .select2-selection {
        height: calc(1.5em + .75rem + 2px) !important;
        padding-top: 5px;
    }
    .select2-container--bootstrap4 .select2-selection__rendered {
        font-weight: 600;
        color: #0d6efd;
        font-size: 1.05em;
    }
    /* === CSS CẬP NHẬT CHO DANH SÁCH LỰA CHỌN === */
    .select2-results__option {
        font-size: 1.05em; /* Tăng kích thước chữ trong danh sách */
        padding: 8px 12px;   /* Tăng khoảng cách cho dễ bấm */
    }
    .select2-results__option--highlighted {
        background-color: #4e73df !important; /* Đổi màu nền khi chọn */
        color: white !important;
    }
</style>

<div class="container-fluid">
    <form action="/quanlybanhang/modules/products/add.php<?= $is_edit_mode ? '?id=' . $product_id : '' ?>" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="prd_id" value="<?php echo $product_id; ?>">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-<?= $is_edit_mode ? 'edit' : 'plus-circle' ?> mr-2"></i>
                    <?= $is_edit_mode ? 'Chỉnh sửa sản phẩm' : 'Tạo sản phẩm' ?>
                </h6>
                <div>
                    <a href="/quanlybanhang/modules/products/list.php" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left mr-1"></i> Trở về</a>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-check mr-1"></i> Lưu</button>
                </div>
            </div>
            <div class="card-body">
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger">
                        <?php foreach ($errors as $error) echo "<p class='mb-0'>$error</p>"; ?>
                    </div>
                <?php endif; ?>
                
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-section">
                            <h5>Thông tin cơ bản</h5>
                            <div class="form-group">
                                <label>Tên sản phẩm <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="prd_name" value="<?= htmlspecialchars($display_data['prd_name'] ?? '') ?>" required>
                            </div>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Giá vốn</label>
                                        <input type="text" class="form-control" name="prd_origin_price" value="<?= number_format($display_data['prd_origin_price'] ?? 0) ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Giá bán lẻ <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" name="prd_sell_price" value="<?= number_format($display_data['prd_sell_price'] ?? 0) ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Giá bán sỉ</label>
                                        <input type="text" class="form-control" name="prd_sell_price2" value="<?= number_format($display_data['prd_sell_price2'] ?? 0) ?>">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Nhà sản xuất</label>
                                <div class="input-group">
                                    <select class="form-control select2-init" name="prd_manufacture_id" id="main_manufacturer_id">
                                        <?php foreach ($manufacturers_list as $item) echo "<option value='{$item['id']}' ".((($display_data['prd_manufacture_id'] ?? 0) == $item['id']) ? 'selected' : '').">".htmlspecialchars($item['prd_manuf_name'])."</option>"; ?>
                                    </select>
                                    <button class="btn btn-outline-secondary btn-quick-manage" type="button" data-type="manufacturer" data-title="Quản lý nhà sản xuất">+</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-section">
                            <h5>Phân loại & Quy cách</h5>
                            <div class="form-group"><label>Mã sản phẩm</label><input type="text" class="form-control" name="prd_code" value="<?= htmlspecialchars($display_data['prd_code'] ?? '') ?>" placeholder="Tự động sinh nếu trống"></div>
                            <div class="form-group">
                                <label>Danh mục</label>
                                <div class="input-group">
                                    <select class="form-control select2-init" name="prd_group_id" id="main_category_id">
                                        <?php foreach ($categories_list as $item) echo "<option value='{$item['id']}' ".((($display_data['prd_group_id'] ?? 0) == $item['id']) ? 'selected' : '').">".htmlspecialchars($item['prd_group_name'])."</option>"; ?>
                                    </select>
                                    <button class="btn btn-outline-secondary btn-quick-manage" type="button" data-type="category" data-title="Quản lý danh mục">+</button>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Đơn vị tính</label>
                                <div class="input-group">
                                    <select class="form-control select2-init" name="prd_unit_id" id="main_unit_id">
                                        <?php foreach ($units_list as $item) echo "<option value='{$item['id']}' ".((($display_data['prd_unit_id'] ?? 0) == $item['id']) ? 'selected' : '').">".htmlspecialchars($item['prd_unit_name'])."</option>"; ?>
                                    </select>
                                    <button class="btn btn-outline-secondary btn-quick-manage" type="button" data-type="unit" data-title="Quản lý đơn vị tính">+</button>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6"><div class="form-group"><label>Tên quy cách</label><input type="text" class="form-control" name="prd_tenquycach" value="<?= htmlspecialchars($display_data['prd_tenquycach'] ?? '') ?>" placeholder="Vd: Thùng"></div></div>
                                <div class="col-md-6"><div class="form-group"><label>Quy cách (SL)</label><input type="number" class="form-control" name="prd_quycach" value="<?= intval($display_data['prd_quycach'] ?? 0) ?>" placeholder="Vd: 24"></div></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<div class="modal fade" id="quickManageModal" tabindex="-1"><div class="modal-dialog modal-lg"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="quickManageModalTitle"></h5><button type="button" class="close" data-dismiss="modal">&times;</button></div><div class="modal-body"><ul class="nav nav-tabs"><li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#list-tab-pane">Danh sách</a></li><li class="nav-item"><a class="nav-link" data-toggle="tab" href="#add-tab-pane">Tạo mới</a></li></ul><div class="tab-content pt-3"><div class="tab-pane fade show active" id="list-tab-pane"><div class="table-responsive"><table class="table table-hover"><thead><tr><th>ID</th><th>Tên</th><th class="text-center">Hành động</th></tr></thead><tbody id="modal-item-list"></tbody></table></div></div><div class="tab-pane fade" id="add-tab-pane"><form id="modal-add-form"><div class="form-group"><label class="form-label">Nhập tên mới:</label><input type="text" class="form-control" id="modal-new-name" required></div><button type="submit" class="btn btn-primary mt-2">Lưu</button></form></div></div></div></div></div></div>

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

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('.select2-init').select2({ theme: 'bootstrap4' });
    let currentType = '';
    const modal = $('#quickManageModal');
    $('.btn-quick-manage').on('click', function() {
        currentType = $(this).data('type');
        $('#quickManageModalTitle').text($(this).data('title'));
        loadModalList();
        modal.modal('show');
    });
    function loadModalList() {
        $.ajax({
            url: '/quanlybanhang/ajax/quick_manage_ajax.php', type: 'GET', data: { action: 'get_list', type: currentType },
            success: function(res) {
                const listBody = $('#modal-item-list'); listBody.empty();
                if (res.status === 'success' && res.data.length > 0) {
                    res.data.forEach(item => {
                        listBody.append(`<tr data-id="${item.id}" data-name="${item.name}"><td>${item.id}</td><td><span class="view-mode">${item.name}</span><input type="text" class="form-control form-control-sm edit-mode" value="${item.name}" style="display:none;"></td><td class="text-center" style="width: 120px;"><button class="btn btn-sm btn-info btn-edit view-mode"><i class="fas fa-edit"></i></button><button class="btn btn-sm btn-danger btn-delete view-mode"><i class="fas fa-trash"></i></button><button class="btn btn-sm btn-success btn-save edit-mode" style="display:none;"><i class="fas fa-check"></i></button><button class="btn btn-sm btn-secondary btn-cancel edit-mode" style="display:none;"><i class="fas fa-times"></i></button></td></tr>`);
                    });
                } else { listBody.append('<tr><td colspan="3" class="text-center">Chưa có dữ liệu.</td></tr>'); }
            }
        });
    }
    $('#modal-add-form').on('submit', function(e) { e.preventDefault();
        const newName = $('#modal-new-name').val().trim();
        if(newName === '') { alert('Tên không được để trống.'); return; }
        $.ajax({
            url: '/quanlybanhang/ajax/quick_manage_ajax.php', type: 'POST', dataType: 'json', data: { action: 'add', type: currentType, name: newName },
            success: function(res) {
                if (res.status === 'success') {
                    $('#modal-new-name').val('');
                    $('.nav-tabs a[href="#list-tab-pane"]').tab('show');
                    loadModalList();
                    refreshMainDropdown(res.new_item.id);
                } else { alert(res.message); }
            }
        });
    });
    $('#modal-item-list').on('click', '.btn-edit', function() { $(this).closest('tr').find('.view-mode, .edit-mode').toggle(); });
    $('#modal-item-list').on('click', '.btn-cancel', function() { $(this).closest('tr').find('.edit-mode').hide().siblings('.view-mode').show(); });
    $('#modal-item-list').on('click', '.btn-save', function() {
        const row = $(this).closest('tr');
        const id = row.data('id');
        const newName = row.find('input.edit-mode').val().trim();
        $.ajax({
            url: '/quanlybanhang/ajax/quick_manage_ajax.php', type: 'POST', data: { action: 'update', type: currentType, id: id, name: newName }, dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    row.find('span.view-mode').text(newName); row.find('.edit-mode').hide().siblings('.view-mode').show();
                    refreshMainDropdown(id);
                } else { alert(res.message); }
            }
        });
    });
    $('#modal-item-list').on('click', '.btn-delete', function() {
        if (confirm('Bạn có chắc chắn muốn xóa mục này?')) {
            const id = $(this).closest('tr').data('id');
            $.ajax({
                url: '/quanlybanhang/ajax/quick_manage_ajax.php', type: 'POST', data: { action: 'delete', type: currentType, id: id }, dataType: 'json',
                success: function(res) {
                    alert(res.message);
                    if (res.status === 'success') {
                        loadModalList();
                        refreshMainDropdown();
                    }
                }
            });
        }
    });
    function refreshMainDropdown(selectedId = null) {
        const dropdown = $(`#main_${currentType}_id`);
        $.ajax({
            url: '/quanlybanhang/ajax/quick_manage_ajax.php', type: 'GET', data: { action: 'get_list', type: currentType },
            success: function(res) {
                if (res.status === 'success') {
                    const currentValue = selectedId || dropdown.val();
                    dropdown.empty();
                    res.data.forEach(item => { dropdown.append($('<option>', { value: item.id, text: item.name })); });
                    dropdown.val(currentValue).trigger('change');
                }
            }
        });
    }
});
</script>