<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('settings_access');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $settings = $_POST['settings'] ?? [];
    foreach ($settings as $key => $value) {
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, setting_group) VALUES (?, ?, 'general') ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute([$key, $value, $value]);
    }

    // Handle logo upload
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] !== UPLOAD_ERR_NO_FILE) {
        $uploadDir = BASE_PATH . 'assets' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'logo' . DIRECTORY_SEPARATOR;
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $file = $_FILES['logo'];
        $uploadError = null;

        if ($file['error'] === UPLOAD_ERR_INI_SIZE || $file['error'] === UPLOAD_ERR_FORM_SIZE) {
            $uploadError = 'File is too large. Maximum size is 5MB.';
        } elseif ($file['error'] !== UPLOAD_ERR_OK) {
            $uploadError = 'Upload failed with error code: ' . $file['error'];
        } else {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'webp'];
            if (!in_array($ext, $allowed)) {
                $uploadError = 'Invalid file type. Allowed: jpg, jpeg, png, webp.';
            } elseif ($file['size'] > 5 * 1024 * 1024) {
                $uploadError = 'File is too large. Maximum size is 5MB.';
            } else {
                $filename = 'logo_' . date('Ymd_His') . '_' . random_int(1000, 9999) . '.' . $ext;
                $destPath = $uploadDir . $filename;
                if (move_uploaded_file($file['tmp_name'], $destPath)) {
                    $relativePath = 'assets/uploads/logo/' . $filename;
                    $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, setting_group) VALUES ('shop_logo', ?, 'general') ON DUPLICATE KEY UPDATE setting_value = ?");
                    $stmt->execute([$relativePath, $relativePath]);
                } else {
                    $uploadError = 'Failed to move uploaded file. Check folder permissions.';
                }
            }
        }

        if ($uploadError) {
            $_SESSION['error'] = $uploadError;
        }
    }

    $_SESSION['success'] = 'Settings saved successfully.';
    header('Location: shop_settings.php'); exit;
}

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

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-cog me-2"></i>Shop Settings</h4>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">General Settings</div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">Shop Name</label>
                                <input type="text" name="settings[shop_name]" class="form-control" value="<?= htmlspecialchars($all_settings['shop_name'] ?? '') ?>">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Address</label>
                                <textarea name="settings[shop_address]" class="form-control" rows="2"><?= htmlspecialchars($all_settings['shop_address'] ?? '') ?></textarea>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Phone</label>
                                    <input type="text" name="settings[shop_phone]" class="form-control" value="<?= htmlspecialchars($all_settings['shop_phone'] ?? '') ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Email</label>
                                    <input type="email" name="settings[shop_email]" class="form-control" value="<?= htmlspecialchars($all_settings['shop_email'] ?? '') ?>">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Website</label>
                                <input type="text" name="settings[shop_website]" class="form-control" value="<?= htmlspecialchars($all_settings['shop_website'] ?? '') ?>">
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Currency</label>
                                    <input type="text" name="settings[currency]" class="form-control" value="<?= htmlspecialchars($all_settings['currency'] ?? 'LKR') ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Currency Symbol</label>
                                    <input type="text" name="settings[currency_symbol]" class="form-control" value="<?= htmlspecialchars($all_settings['currency_symbol'] ?? 'Rs.') ?>">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Shop Logo</label>
                                <input type="file" name="logo" class="form-control" accept="image/jpeg,image/png,image/webp" onchange="previewLogo(event)">
                                <?php if (!empty($all_settings['shop_logo'])): ?>
                                <div class="mt-2">
                                    <img src="<?= htmlspecialchars(getShopLogoUrl()) ?>?v=<?= time() ?>" alt="Shop Logo" style="max-height:80px;" id="logoPreview">
                                    <div><small class="text-muted">Current: <?= htmlspecialchars($all_settings['shop_logo']) ?></small></div>
                                </div>
                                <?php else: ?>
                                <div class="mt-2">
                                    <img src="<?= htmlspecialchars(getShopLogoUrl()) ?>?v=<?= time() ?>" alt="Default Logo" style="max-height:80px;" id="logoPreview">
                                </div>
                                <?php endif; ?>
                            </div>
                            <script>
                            function previewLogo(event) {
                                var reader = new FileReader();
                                reader.onload = function() {
                                    var output = document.getElementById('logoPreview');
                                    if (output) {
                                        output.src = reader.result;
                                    } else {
                                        var img = document.createElement('img');
                                        img.src = reader.result;
                                        img.style.maxHeight = '80px';
                                        img.id = 'logoPreview';
                                        event.target.parentNode.appendChild(img);
                                    }
                                };
                                if (event.target.files[0]) {
                                    reader.readAsDataURL(event.target.files[0]);
                                }
                            }
                            </script>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">Invoice & Tax Settings</div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Invoice Prefix</label>
                                    <input type="text" name="settings[invoice_prefix]" class="form-control" value="<?= htmlspecialchars($all_settings['invoice_prefix'] ?? 'INV-') ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Repair Job Prefix</label>
                                    <input type="text" name="settings[repair_prefix]" class="form-control" value="<?= htmlspecialchars($all_settings['repair_prefix'] ?? 'JOB-') ?>">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Tax Name</label>
                                    <input type="text" name="settings[tax_name]" class="form-control" value="<?= htmlspecialchars($all_settings['tax_name'] ?? 'VAT') ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Tax Rate (%)</label>
                                    <input type="number" step="0.01" name="settings[tax_rate]" class="form-control" value="<?= htmlspecialchars($all_settings['tax_rate'] ?? '0') ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Low Stock Alert</label>
                                    <input type="number" name="settings[low_stock_alert]" class="form-control" value="<?= htmlspecialchars($all_settings['low_stock_alert'] ?? '5') ?>">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Warranty Terms</label>
                                <textarea name="settings[warranty_terms]" class="form-control" rows="3"><?= htmlspecialchars($all_settings['warranty_terms'] ?? '') ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Invoice Terms & Conditions</label>
                                <textarea name="settings[invoice_terms]" class="form-control" rows="3"><?= htmlspecialchars($all_settings['invoice_terms'] ?? '') ?></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-header">Notification Settings</div>
                        <div class="card-body">
                            <p class="text-muted">SMS and WhatsApp gateway settings. Configure your API credentials here.</p>
                            <div class="mb-3">
                                <label class="form-label">SMS Gateway API Key</label>
                                <input type="text" name="settings[sms_api_key]" class="form-control" value="<?= htmlspecialchars($all_settings['sms_api_key'] ?? '') ?>" placeholder="Enter API key">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">SMS Sender ID</label>
                                <input type="text" name="settings[sms_sender_id]" class="form-control" value="<?= htmlspecialchars($all_settings['sms_sender_id'] ?? '') ?>">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">WhatsApp API Key</label>
                                <input type="text" name="settings[whatsapp_api_key]" class="form-control" value="<?= htmlspecialchars($all_settings['whatsapp_api_key'] ?? '') ?>" placeholder="Enter WhatsApp API key">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">WhatsApp Number</label>
                                <input type="text" name="settings[whatsapp_number]" class="form-control" value="<?= htmlspecialchars($all_settings['whatsapp_number'] ?? '') ?>">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-save me-1"></i>Save Settings</button>
            </div>
        </form>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
