<?php
session_start();
date_default_timezone_set('Africa/Lagos');
require __DIR__ . '/../config.php';
require __DIR__ . '/includes/auth_init.php';

if (!$isAdmin) {
    $_SESSION['flash_error'] = "You don't have permission to manage statutory settings.";
    header("Location: dashboard.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_company'])) {
    $companyName = trim($_POST['company_name'] ?? 'Your Company');
    $footerText = trim($_POST['footer_text'] ?? '');

    $existing = $conn->query("SELECT * FROM company_settings ORDER BY id DESC LIMIT 1")->fetch_assoc();
    $logoPath = $existing['logo_path'] ?? null;

    // Handle logo upload if a new file was provided
    if (!empty($_FILES['logo']['name']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $allowedExt = ['png', 'jpg', 'jpeg', 'gif', 'webp'];
        $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, $allowedExt) && $_FILES['logo']['size'] <= 2 * 1024 * 1024) {
            $uploadsDir = __DIR__ . '/uploads';
            if (!is_dir($uploadsDir)) { mkdir($uploadsDir, 0755, true); }
            $newFilename = 'company_logo_' . time() . '.' . $ext;
            $destination = $uploadsDir . '/' . $newFilename;
            if (move_uploaded_file($_FILES['logo']['tmp_name'], $destination)) {
                // Remove the old logo file if one existed
                if ($logoPath && file_exists(__DIR__ . '/' . $logoPath)) {
                    @unlink(__DIR__ . '/' . $logoPath);
                }
                $logoPath = 'uploads/' . $newFilename;
            } else {
                $_SESSION['flash_error'] = "Logo upload failed -- check that the uploads/ folder is writable.";
            }
        } else {
            $_SESSION['flash_error'] = "Logo must be PNG/JPG/GIF/WEBP and under 2MB.";
        }
    }

    if ($existing) {
        $stmt = $conn->prepare("UPDATE company_settings SET company_name = ?, logo_path = ?, footer_text = ?, updated_by = ? WHERE id = ?");
        $stmt->bind_param('sssii', $companyName, $logoPath, $footerText, $_SESSION['user_id'], $existing['id']);
    } else {
        $stmt = $conn->prepare("INSERT INTO company_settings (company_name, logo_path, footer_text, updated_by) VALUES (?, ?, ?, ?)");
        $stmt->bind_param('sssi', $companyName, $logoPath, $footerText, $_SESSION['user_id']);
    }
    $stmt->execute();
    $stmt->close();

    if (empty($_SESSION['flash_error'])) {
        $_SESSION['flash_success'] = "Company letterhead updated.";
    }
    header("Location: settings.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settings'])) {
    $keys = ['pension_employee_pct','pension_employer_pct','nhf_pct','nhis_pct','rent_relief_pct','rent_relief_cap','paye_tax_free_threshold'];
    foreach ($keys as $key) {
        $value = isset($_POST[$key]) ? (float) $_POST[$key] : 0;
        $active = isset($_POST[$key . '_active']) ? 1 : 0;
        $stmt = $conn->prepare("UPDATE statutory_settings SET setting_value = ?, is_active = ? WHERE setting_key = ?");
        $stmt->bind_param('dis', $value, $active, $key);
        $stmt->execute();
        $stmt->close();
    }
    $_SESSION['flash_success'] = "Statutory settings updated.";
    header("Location: settings.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_band'])) {
    $year = (int) $_POST['effective_year'];
    $order = (int) $_POST['band_order'];
    $min = (float) $_POST['min_amount'];
    $max = $_POST['max_amount'] === '' ? null : (float) $_POST['max_amount'];
    $rate = (float) $_POST['rate'];
    $label = trim($_POST['label']);

    $stmt = $conn->prepare("INSERT INTO tax_bands (effective_year, band_order, min_amount, max_amount, rate, label) VALUES (?, ?, ?, ?, ?, ?)");
    // max_amount may be NULL (an unlimited top band) -- mysqli allows binding NULL with a 'd' type
    $stmt->bind_param('iiddds', $year, $order, $min, $max, $rate, $label);
    try {
        $stmt->execute();
        $_SESSION['flash_success'] = "Tax band added.";
    } catch (mysqli_sql_exception $e) {
        if ($e->getCode() === 1062) {
            $_SESSION['flash_error'] = "Band $order for $year already exists. Use a different band order number, or edit the existing band directly in the database.";
        } else {
            $_SESSION['flash_error'] = "Could not add tax band: " . $e->getMessage();
        }
    }
    $stmt->close();
    header("Location: settings.php");
    exit;
}

$settings = [];
$res = $conn->query("SELECT * FROM statutory_settings");
while ($row = $res->fetch_assoc()) {
    $settings[$row['setting_key']] = $row;
}

$companySettings = $conn->query("SELECT * FROM company_settings ORDER BY id DESC LIMIT 1")->fetch_assoc();

$currentYear = (int) date('Y');
$bands = $conn->query("SELECT * FROM tax_bands WHERE effective_year = (SELECT MAX(effective_year) FROM tax_bands WHERE effective_year <= $currentYear) ORDER BY band_order ASC");

function settingRow($key, $label, $settings, $suffix = '%') {
    $s = $settings[$key];
    echo '<div class="grid grid-cols-1 sm:grid-cols-4 gap-3 items-center py-3 border-b border-slate-100 last:border-0">';
    echo '<label class="text-xs font-bold text-slate-700 sm:col-span-2">' . h($label) . '</label>';
    echo '<div class="flex items-center gap-2">';
    echo '<input type="number" step="0.01" name="' . $key . '" value="' . h($s['setting_value']) . '" class="w-full text-sm border border-slate-200 rounded-lg px-3 py-1.5">';
    echo '<span class="text-xs text-slate-500">' . $suffix . '</span>';
    echo '</div>';
    echo '<div class="flex items-center gap-2">';
    echo '<input type="checkbox" name="' . $key . '_active" ' . ($s['is_active'] ? 'checked' : '') . ' class="rounded">';
    echo '<label class="text-xs font-bold text-slate-600">Enabled</label>';
    echo '</div>';
    echo '</div>';
}
?>
<?php
$pageTitle = 'Statutory Settings';
$pageSubtitle = 'Payroll Module';
require __DIR__ . '/includes/layout_header.php';
?>

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-1">Company Letterhead</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-4">Shown on printed payroll reports -- logo, company name, and footer text (e.g. address, RC number, or a disclaimer).</p>
    <form method="POST" enctype="multipart/form-data" class="grid grid-cols-1 sm:grid-cols-2 gap-4 items-end">
        <div class="sm:col-span-2 flex items-center gap-4">
            <?php if (!empty($companySettings['logo_path'])): ?>
                <img src="<?= h($companySettings['logo_path']); ?>?v=<?= time(); ?>" alt="Company logo" class="h-14 w-14 object-contain rounded-lg border border-slate-200 bg-slate-50 p-1">
            <?php else: ?>
                <div class="h-14 w-14 rounded-lg border border-dashed border-slate-300 bg-slate-50 flex items-center justify-center text-[9px] text-slate-400 font-bold uppercase text-center px-1">No logo</div>
            <?php endif; ?>
            <div class="flex-1">
                <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Logo (PNG/JPG/GIF/WEBP, max 2MB)</label>
                <input type="file" name="logo" accept="image/png,image/jpeg,image/gif,image/webp" class="mt-1 w-full text-xs border border-slate-200 rounded-lg p-2.5 bg-slate-50">
            </div>
        </div>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Company Name</label>
            <input type="text" name="company_name" value="<?= h($companySettings['company_name'] ?? ''); ?>" placeholder="Your Company Ltd"
                   class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
        </div>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Footer Text</label>
            <input type="text" name="footer_text" value="<?= h($companySettings['footer_text'] ?? ''); ?>" placeholder="e.g. 123 Main St, Lagos • RC1234567"
                   class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
        </div>
        <div class="sm:col-span-2">
            <button type="submit" name="save_company" class="bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-black uppercase tracking-wider px-5 py-2.5 rounded-lg transition active:scale-95 border border-indigo-700">
                Save Letterhead
            </button>
        </div>
    </form>
</div>

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-1">Statutory Deduction Defaults</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-4">Toggle any statutory deduction off if it doesn't apply to your organization. These apply to every employee automatically.</p>
    <form method="POST" class="space-y-1">
        <?php
        settingRow('pension_employee_pct', 'Pension - Employee Contribution', $settings);
        settingRow('pension_employer_pct', 'Pension - Employer Contribution (record only)', $settings);
        settingRow('nhf_pct', 'NHF (National Housing Fund)', $settings);
        settingRow('nhis_pct', 'NHIS Contribution', $settings);
        settingRow('rent_relief_pct', 'Rent Relief (% of annual rent)', $settings);
        settingRow('rent_relief_cap', 'Rent Relief Cap (NGN/year)', $settings, 'NGN');
        settingRow('paye_tax_free_threshold', 'PAYE Tax-Free Threshold (NGN/year)', $settings, 'NGN');
        ?>
        <div class="pt-4">
            <button type="submit" name="save_settings" class="bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-black uppercase tracking-wider px-5 py-2.5 rounded-lg transition active:scale-95 border border-indigo-700">
                Save Settings
            </button>
        </div>
    </form>
</div>

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-1">PAYE Tax Bands</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-4">Currently active bands (Nigeria Tax Act 2025, effective 1 Jan 2026). Add a new year's bands here if the law changes again — the engine always uses the most recent effective year.</p>
    <div class="overflow-x-auto mb-4">
        <table class="w-full text-sm">
            <thead class="bg-slate-50 text-slate-400 uppercase text-[9px] font-black tracking-wider">
                <tr>
                    <th class="text-left p-3">Order</th>
                    <th class="text-left p-3">Min (NGN)</th>
                    <th class="text-left p-3">Max (NGN)</th>
                    <th class="text-left p-3">Rate</th>
                    <th class="text-left p-3">Label</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php while ($b = $bands->fetch_assoc()): ?>
                <tr class="hover:bg-slate-50/50 transition">
                    <td class="p-3"><?= $b['band_order']; ?></td>
                    <td class="p-3"><?= number_format($b['min_amount']); ?></td>
                    <td class="p-3"><?= $b['max_amount'] !== null ? number_format($b['max_amount']) : 'No limit'; ?></td>
                    <td class="p-3 font-bold"><?= $b['rate']; ?>%</td>
                    <td class="p-3 text-slate-500"><?= h($b['label']); ?></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>

    <details class="text-xs">
        <summary class="cursor-pointer font-bold text-indigo-700">+ Add a new tax band (for a future law change)</summary>
        <form method="POST" class="grid grid-cols-2 sm:grid-cols-6 gap-3 mt-3 items-end">
            <div><label class="text-[10px] font-black text-slate-400 uppercase">Year</label><input type="number" name="effective_year" value="<?= date('Y')+1; ?>" class="mt-1 w-full text-sm border border-slate-200 rounded-lg px-2 py-1.5"></div>
            <div><label class="text-[10px] font-black text-slate-400 uppercase">Order</label><input type="number" name="band_order" value="1" class="mt-1 w-full text-sm border border-slate-200 rounded-lg px-2 py-1.5"></div>
            <div><label class="text-[10px] font-black text-slate-400 uppercase">Min</label><input type="number" step="0.01" name="min_amount" class="mt-1 w-full text-sm border border-slate-200 rounded-lg px-2 py-1.5"></div>
            <div><label class="text-[10px] font-black text-slate-400 uppercase">Max (blank=∞)</label><input type="number" step="0.01" name="max_amount" class="mt-1 w-full text-sm border border-slate-200 rounded-lg px-2 py-1.5"></div>
            <div><label class="text-[10px] font-black text-slate-400 uppercase">Rate %</label><input type="number" step="0.01" name="rate" class="mt-1 w-full text-sm border border-slate-200 rounded-lg px-2 py-1.5"></div>
            <div><label class="text-[10px] font-black text-slate-400 uppercase">Label</label><input type="text" name="label" class="mt-1 w-full text-sm border border-slate-200 rounded-lg px-2 py-1.5"></div>
            <div class="col-span-full"><button type="submit" name="add_band" class="bg-slate-900 hover:bg-slate-800 text-white text-xs font-black uppercase px-4 py-2 rounded-lg transition active:scale-95 border border-slate-950">Add Band</button></div>
        </form>
    </details>
</div>

<?php require __DIR__ . '/includes/layout_footer.php'; ?>