<?php
$pageTitle = 'Settings';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../auth/session.php';

require_login();
require_permission($pdo, 'settings.manage');

require_once __DIR__ . '/../includes/header.php';

$allowedKeys = [
    'store_name',
    'store_logo_url',
    'store_address',
    'store_phone',
    'currency_symbol',
    'receipt_footer',
    'tax_rate',
    'low_stock_threshold',
    'thermal_printer_width_mm',
    'enable_customer_tracking',
    'require_customer_on_sale',
    'enable_senior_discount',
    'enable_pwd_discount',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customerTrackingEnabled = isset($_POST['enable_customer_tracking']) ? '1' : '0';
    $_POST['enable_customer_tracking'] = $customerTrackingEnabled;
    $_POST['require_customer_on_sale'] = $customerTrackingEnabled === '1' && isset($_POST['require_customer_on_sale']) ? '1' : '0';
    $_POST['enable_senior_discount'] = isset($_POST['enable_senior_discount']) ? '1' : '0';
    $_POST['enable_pwd_discount'] = isset($_POST['enable_pwd_discount']) ? '1' : '0';

    foreach ($allowedKeys as $key) {
        $value = trim($_POST[$key] ?? '');
        $stmt = $pdo->prepare('
            INSERT INTO settings(setting_key, setting_value)
            VALUES(?, ?)
            ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
        ');
        $stmt->execute([$key, $value]);
    }
    echo '<div class="alert alert-success">Settings saved successfully.</div>';
}

$settings = [];
$stmt = $pdo->query('SELECT setting_key, setting_value FROM settings');
foreach ($stmt as $row) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

$customerTrackingEnabled = ($settings['enable_customer_tracking'] ?? '1') === '1';
$requireCustomerOnSale = $customerTrackingEnabled && ($settings['require_customer_on_sale'] ?? '0') === '1';
$seniorDiscountEnabled = ($settings['enable_senior_discount'] ?? '1') === '1';
$pwdDiscountEnabled = ($settings['enable_pwd_discount'] ?? '1') === '1';

function setting_value(array $settings, string $key, string $default = ''): string
{
    return htmlspecialchars($settings[$key] ?? $default, ENT_QUOTES, 'UTF-8');
}
?>
<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h4 class="mb-0">Settings</h4>
        <small class="text-muted">Store profile, receipt, and thermal printer settings.</small>
    </div>
</div>

<form method="post" class="table-card">
    <div class="row g-3">
        <div class="col-md-6">
            <label class="form-label">Store Name</label>
            <input type="text" name="store_name" class="form-control" value="<?= setting_value($settings, 'store_name', 'POS STORE') ?>">
        </div>
        <div class="col-md-6">
            <label class="form-label">Store Phone</label>
            <input type="text" name="store_phone" class="form-control" value="<?= setting_value($settings, 'store_phone') ?>">
        </div>
        <div class="col-12">
            <label class="form-label">Store Address</label>
            <input type="text" name="store_address" class="form-control" value="<?= setting_value($settings, 'store_address', 'Main Branch') ?>">
        </div>
        <div class="col-12">
            <label class="form-label">Store Logo URL / Path</label>
            <input type="text" name="store_logo_url" class="form-control" value="<?= setting_value($settings, 'store_logo_url') ?>" placeholder="assets/img/logo.png or https://example.com/logo.png">
        </div>
        <div class="col-md-3">
            <label class="form-label">Currency Symbol</label>
            <input type="text" name="currency_symbol" class="form-control" value="<?= setting_value($settings, 'currency_symbol', '₱') ?>">
        </div>
        <div class="col-md-3">
            <label class="form-label">Tax Rate (%)</label>
            <input type="number" step="0.01" name="tax_rate" class="form-control" value="<?= setting_value($settings, 'tax_rate', '0') ?>">
        </div>
        <div class="col-md-3">
            <label class="form-label">Default Low Stock Threshold</label>
            <input type="number" name="low_stock_threshold" class="form-control" value="<?= setting_value($settings, 'low_stock_threshold', '5') ?>">
        </div>
        <div class="col-md-3">
            <label class="form-label">Thermal Printer Width</label>
            <select name="thermal_printer_width_mm" class="form-select">
                <?php $width = $settings['thermal_printer_width_mm'] ?? '58'; ?>
                <option value="58" <?= $width === '58' ? 'selected' : '' ?>>58mm</option>
                <option value="80" <?= $width === '80' ? 'selected' : '' ?>>80mm</option>
            </select>
        </div>
        <div class="col-12">
            <label class="form-label">Receipt Footer</label>
            <textarea name="receipt_footer" class="form-control" rows="3"><?= setting_value($settings, 'receipt_footer', 'Thank you for shopping!') ?></textarea>
        </div>
        <div class="col-md-6">
            <div class="border rounded p-3 h-100">
                <div class="form-check form-switch">
                    <input
                        class="form-check-input"
                        type="checkbox"
                        role="switch"
                        id="enableCustomerTracking"
                        name="enable_customer_tracking"
                        value="1"
                        <?= $customerTrackingEnabled ? 'checked' : '' ?>
                    >
                    <label class="form-check-label fw-semibold" for="enableCustomerTracking">Enable Customer Tracking</label>
                </div>
                <small class="text-muted d-block mt-2">Show customer selection on POS sales.</small>
            </div>
        </div>
        <div class="col-md-6">
            <div class="border rounded p-3 h-100">
                <div class="form-check form-switch">
                    <input
                        class="form-check-input"
                        type="checkbox"
                        role="switch"
                        id="requireCustomerOnSale"
                        name="require_customer_on_sale"
                        value="1"
                        <?= $requireCustomerOnSale ? 'checked' : '' ?>
                        <?= $customerTrackingEnabled ? '' : 'disabled' ?>
                    >
                    <label class="form-check-label fw-semibold" for="requireCustomerOnSale">Require Customer On Sale</label>
                </div>
                <small class="text-muted d-block mt-2">Require a selected customer before checkout when tracking is enabled.</small>
            </div>
        </div>
        <div class="col-md-6">
            <div class="border rounded p-3 h-100">
                <div class="form-check form-switch">
                    <input
                        class="form-check-input"
                        type="checkbox"
                        role="switch"
                        id="enableSeniorDiscount"
                        name="enable_senior_discount"
                        value="1"
                        <?= $seniorDiscountEnabled ? 'checked' : '' ?>
                    >
                    <label class="form-check-label fw-semibold" for="enableSeniorDiscount">Enable Senior Discount</label>
                </div>
                <small class="text-muted d-block mt-2">Allow Senior discount selection in POS when a customer is selected.</small>
            </div>
        </div>
        <div class="col-md-6">
            <div class="border rounded p-3 h-100">
                <div class="form-check form-switch">
                    <input
                        class="form-check-input"
                        type="checkbox"
                        role="switch"
                        id="enablePwdDiscount"
                        name="enable_pwd_discount"
                        value="1"
                        <?= $pwdDiscountEnabled ? 'checked' : '' ?>
                    >
                    <label class="form-check-label fw-semibold" for="enablePwdDiscount">Enable PWD Discount</label>
                </div>
                <small class="text-muted d-block mt-2">Allow PWD discount selection in POS when a customer is selected.</small>
            </div>
        </div>
    </div>
    <button class="btn btn-primary mt-4"><i class="bi bi-save"></i> Save Settings</button>
</form>

<div class="table-card mt-3">
    <h6>Thermal Receipt Test</h6>
    <p class="text-muted mb-2">Open any completed sale receipt, then click Print Receipt. Browser print settings should use the matching paper width.</p>
    <a href="<?= app_url('sales/index.php') ?>" class="btn btn-outline-primary btn-sm">Go to Sales History</a>
</div>

<script>
const trackingSwitch = document.getElementById('enableCustomerTracking');
const requireSwitch = document.getElementById('requireCustomerOnSale');

function syncCustomerTrackingControls() {
    if (!trackingSwitch || !requireSwitch) {
        return;
    }

    requireSwitch.disabled = !trackingSwitch.checked;
    if (!trackingSwitch.checked) {
        requireSwitch.checked = false;
    }
}

if (trackingSwitch) {
    trackingSwitch.addEventListener('change', syncCustomerTrackingControls);
}
syncCustomerTrackingControls();
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
