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

$settings = [];
$result = $conn->query("SELECT content FROM cms_templates WHERE id = 1");
if ($result && $result->num_rows > 0) {
    $content_json = $result->fetch_assoc()['content'];
    $settings = json_decode($content_json, true);
}
?>

<style>
    .nav-tabs .nav-link.active { font-weight: bold; color: #4e73df; }
    .card-header h6 { line-height: 1.5; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Thiết lập hệ thống</h1>

    <ul class="nav nav-tabs mb-4">
        <li class="nav-item"><a class="nav-link" href="/quanlybanhang/modules/users/list.php"><i class="fas fa-user fa-sm me-2"></i>Nhân viên</a></li>
        <li class="nav-item"><a class="nav-link" href="/quanlybanhang/modules/users/permissions.php"><i class="fas fa-user-shield fa-sm me-2"></i>Phân quyền</a></li>
        <li class="nav-item"><a class="nav-link active" href="/quanlybanhang/modules/settings/print_config.php"><i class="fas fa-print fa-sm me-2"></i>Cài đặt trang in</a></li>
        <li class="nav-item"><a class="nav-link" href="/quanlybanhang/modules/stores/list.php"><i class="fas fa-warehouse fa-sm me-2"></i>Quản lý kho</a></li>
    </ul>

    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Thông tin hiển thị trên chứng từ</h6>
        </div>
        <div class="card-body">
            <form id="print-settings-form" enctype="multipart/form-data">
                <div class="row">
                    <div class="col-md-8">
                        <div class="mb-3"><label for="company_name" class="form-label">Tên công ty / Cửa hàng</label><input type="text" class="form-control" name="company_name" value="<?php echo htmlspecialchars($settings['company_name'] ?? ''); ?>"></div>
                        <div class="mb-3"><label for="company_address" class="form-label">Địa chỉ</label><input type="text" class="form-control" name="company_address" value="<?php echo htmlspecialchars($settings['company_address'] ?? ''); ?>"></div>
                        <div class="mb-3"><label for="company_phone" class="form-label">Số điện thoại</label><input type="text" class="form-control" name="company_phone" value="<?php echo htmlspecialchars($settings['company_phone'] ?? ''); ?>"></div>
                        <div class="mb-3"><label for="company_tax_code" class="form-label">Mã số thuế</label><input type="text" class="form-control" name="company_tax_code" value="<?php echo htmlspecialchars($settings['company_tax_code'] ?? ''); ?>"></div>
                        <hr>
                        <div class="mb-3"><label for="company_specialty_title" class="form-label">Tiêu đề kinh doanh</label><input type="text" class="form-control" name="company_specialty_title" placeholder="Ví dụ: Chuyên KD HMP" value="<?php echo htmlspecialchars($settings['company_specialty_title'] ?? ''); ?>"></div>
                        <div class="mb-3"><label for="company_specialty_items" class="form-label">Nội dung kinh doanh (xuống dòng để tạo danh sách)</label><textarea class="form-control" name="company_specialty_items" rows="3" placeholder="Ví dụ: Hàng P&G, Unilever, Colgate..."><?php echo htmlspecialchars($settings['company_specialty_items'] ?? ''); ?></textarea></div>
                        <hr>
                        <div class="mb-3"><label for="company_bank_info" class="form-label">Tên ngân hàng / Chi nhánh</label><input type="text" class="form-control" name="company_bank_info" placeholder="Ví dụ: Sacombank Cần Thơ" value="<?php echo htmlspecialchars($settings['company_bank_info'] ?? ''); ?>"></div>
                        <div class="mb-3"><label for="company_bank_accounts" class="form-label">Thông tin tài khoản (xuống dòng cho mỗi tài khoản)</label><textarea class="form-control" name="company_bank_accounts" rows="3" placeholder="Ví dụ: 0932.90.51.51 (Võ Nguyên Lý)"><?php echo htmlspecialchars($settings['company_bank_accounts'] ?? ''); ?></textarea></div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3"><label for="company_logo" class="form-label">Logo công ty</label><input class="form-control" type="file" name="company_logo" accept="image/*"></div>
                        <div class="text-center">
                            <p class="text-muted">Logo hiện tại:</p>
                            <img id="logo-preview" src="/quanlybanhang/<?php echo htmlspecialchars($settings['company_logo'] ?? ''); ?>" alt="Logo Preview" class="img-thumbnail" style="max-height: 150px; display: <?php echo empty($settings['company_logo']) ? 'none' : 'block'; ?>;" onerror="this.style.display='none'">
                        </div>
                    </div>
                </div>
                <hr>
                <button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i> Lưu cài đặt</button>
            </form>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>
<script>
$(document).ready(function() {
    $('#print-settings-form').on('submit', function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        formData.append('action', 'save_print_settings');
        const button = $(this).find('button[type="submit"]');
        button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span> Đang lưu...');
        $.ajax({
            url: '/quanlybanhang/ajax/settings_ajax.php', type: 'POST', data: formData,
            contentType: false, processData: false, dataType: 'json',
            success: function(response) {
                alert(response.message);
                if(response.status === 'success' && response.new_logo_path) {
                    $('#logo-preview').attr('src', '/quanlybanhang/' + response.new_logo_path + '?' + new Date().getTime()).show();
                }
            },
            error: function() { alert('Có lỗi xảy ra, không thể kết nối đến máy chủ.'); },
            complete: function() { button.prop('disabled', false).html('<i class="fas fa-save me-2"></i> Lưu cài đặt'); }
        });
    });

    $('input[name="company_logo"]').on('change', function(e) {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = (e) => $('#logo-preview').attr('src', e.target.result).show();
            reader.readAsDataURL(this.files[0]);
        }
    });
});
</script>