<?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);
}
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Cài đặt thông tin trang in</h1>

    <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>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;" onerror="this.style.display='none'">
                        </div>
                    </div>
                </div>
                <hr>
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Lưu cài đặt</button>
            </form>
        </div>
    </div>
</div>

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

<script>
// JavaScript không cần thay đổi, giữ nguyên
$(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"></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).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"></i> Lưu cài đặt'); }
        });
    });
    $('#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>