<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Lodge Settings';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('base_url')) {
    function base_url(string $path = ''): string
    {
        return '/' . ltrim($path, '/');
    }
}

if (!function_exists('settings_alert')) {
    function settings_alert(string $message, string $type = 'success'): string
    {
        return '<div class="alert alert-' . h($type) . '">' . h($message) . '</div>';
    }
}

/**
 * Creates the settings table if it does not already exist.
 * This keeps the page usable even on a fresh PMS install.
 */
if (!function_exists('ensure_lodge_settings_table')) {
    function ensure_lodge_settings_table(PDO $pdo): void
    {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS lodge_settings (
                id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                lodge_name VARCHAR(150) NOT NULL DEFAULT '',
                legal_name VARCHAR(180) NULL,
                tag_line VARCHAR(180) NULL,
                email VARCHAR(150) NULL,
                phone VARCHAR(80) NULL,
                alt_phone VARCHAR(80) NULL,
                website VARCHAR(180) NULL,
                address_line1 VARCHAR(180) NULL,
                address_line2 VARCHAR(180) NULL,
                city VARCHAR(120) NULL,
                state_region VARCHAR(120) NULL,
                country VARCHAR(120) NULL,
                postal_code VARCHAR(50) NULL,
                currency_code VARCHAR(10) NOT NULL DEFAULT 'USD',
                timezone_name VARCHAR(80) NOT NULL DEFAULT 'Africa/Harare',
                check_in_time TIME NULL,
                check_out_time TIME NULL,
                tax_name VARCHAR(80) NULL,
                tax_percent DECIMAL(10,2) NOT NULL DEFAULT 0.00,
                vat_number VARCHAR(80) NULL,
                tin_number VARCHAR(80) NULL,
                company_reg_number VARCHAR(100) NULL,
                invoice_prefix VARCHAR(20) NOT NULL DEFAULT 'INV',
                receipt_prefix VARCHAR(20) NOT NULL DEFAULT 'RCT',
                reservation_prefix VARCHAR(20) NOT NULL DEFAULT 'BK',
                logo_path VARCHAR(255) NULL,
                bank_name VARCHAR(180) NULL,
                bank_account_name VARCHAR(180) NULL,
                bank_account_no VARCHAR(80) NULL,
                bank_branch VARCHAR(120) NULL,
                bank_swift VARCHAR(80) NULL,
                cancellation_policy TEXT NULL,
                payment_terms TEXT NULL,
                terms_and_conditions TEXT NULL,
                invoice_footer TEXT NULL,
                updated_by INT NULL,
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");
    }
}



if (!function_exists('lodge_column_exists')) {
    function lodge_column_exists(PDO $pdo, string $column): bool
    {
        static $cache = [];
        if (array_key_exists($column, $cache)) {
            return $cache[$column];
        }
        try {
            $stmt = $pdo->prepare("\n                SELECT COUNT(*)\n                FROM INFORMATION_SCHEMA.COLUMNS\n                WHERE TABLE_SCHEMA = DATABASE()\n                  AND TABLE_NAME = 'lodge_settings'\n                  AND COLUMN_NAME = :column_name\n            ");
            $stmt->execute([':column_name' => $column]);
            $cache[$column] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            $cache[$column] = false;
        }
        return $cache[$column];
    }
}

if (!function_exists('ensure_lodge_settings_columns')) {
    function ensure_lodge_settings_columns(PDO $pdo): void
    {
        $columns = [
            'vat_number' => "ALTER TABLE lodge_settings ADD COLUMN vat_number VARCHAR(80) NULL AFTER tax_percent",
            'tin_number' => "ALTER TABLE lodge_settings ADD COLUMN tin_number VARCHAR(80) NULL AFTER vat_number",
            'company_reg_number' => "ALTER TABLE lodge_settings ADD COLUMN company_reg_number VARCHAR(100) NULL AFTER tin_number",
        ];

        foreach ($columns as $column => $sql) {
            if (!lodge_column_exists($pdo, $column)) {
                try {
                    $pdo->exec($sql);
                } catch (Throwable $e) {
                    // Ignore duplicate/permission issues so the page can still load.
                }
            }
        }
    }
}

if (!function_exists('fetch_lodge_settings')) {
    function fetch_lodge_settings(PDO $pdo): array
    {
        $stmt = $pdo->query("SELECT * FROM lodge_settings ORDER BY id ASC LIMIT 1");
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            return $row;
        }

        return [
            'id'                  => 0,
            'lodge_name'          => '',
            'legal_name'          => '',
            'tag_line'            => '',
            'email'               => '',
            'phone'               => '',
            'alt_phone'           => '',
            'website'             => '',
            'address_line1'       => '',
            'address_line2'       => '',
            'city'                => '',
            'state_region'        => '',
            'country'             => '',
            'postal_code'         => '',
            'currency_code'       => 'USD',
            'timezone_name'       => 'Africa/Harare',
            'check_in_time'       => '14:00:00',
            'check_out_time'      => '10:00:00',
            'tax_name'            => 'VAT',
            'tax_percent'         => '0.00',
            'vat_number'          => '',
            'tin_number'          => '',
            'company_reg_number'  => '',
            'invoice_prefix'      => 'INV',
            'receipt_prefix'      => 'RCT',
            'reservation_prefix'  => 'BK',
            'logo_path'           => '',
            'bank_name'           => '',
            'bank_account_name'   => '',
            'bank_account_no'     => '',
            'bank_branch'         => '',
            'bank_swift'          => '',
            'cancellation_policy' => '',
            'payment_terms'       => '',
            'terms_and_conditions'=> '',
            'invoice_footer'      => '',
            'updated_by'          => 0,
        ];
    }
}

if (!function_exists('normalise_time_value')) {
    function normalise_time_value(string $value, string $fallback = '00:00:00'): string
    {
        $value = trim($value);
        if ($value === '') {
            return $fallback;
        }

        if (preg_match('/^\d{2}:\d{2}$/', $value)) {
            return $value . ':00';
        }

        if (preg_match('/^\d{2}:\d{2}:\d{2}$/', $value)) {
            return $value;
        }

        return $fallback;
    }
}

if (!function_exists('save_uploaded_logo')) {
    function save_uploaded_logo(array $file): array
    {
        if (($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
            return ['ok' => true, 'path' => null];
        }

        if (($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
            return ['ok' => false, 'message' => 'Logo upload failed.'];
        }

        $tmpName = (string)($file['tmp_name'] ?? '');
        if ($tmpName === '' || !is_uploaded_file($tmpName)) {
            return ['ok' => false, 'message' => 'Invalid uploaded logo file.'];
        }

        $allowed = [
            'image/jpeg' => 'jpg',
            'image/png'  => 'png',
            'image/webp' => 'webp',
            'image/gif'  => 'gif',
        ];

        $mime = function_exists('mime_content_type') ? mime_content_type($tmpName) : '';
        if (!isset($allowed[$mime])) {
            return ['ok' => false, 'message' => 'Logo must be JPG, PNG, GIF, or WEBP.'];
        }

        $uploadDirFs = dirname(__DIR__, 2) . '/uploads/settings';
        $uploadDirWeb = '/rooms/uploads/settings';

        if (!is_dir($uploadDirFs) && !mkdir($uploadDirFs, 0775, true) && !is_dir($uploadDirFs)) {
            return ['ok' => false, 'message' => 'Could not create upload folder for logo.'];
        }

        $filename = 'lodge-logo-' . date('YmdHis') . '-' . mt_rand(1000, 9999) . '.' . $allowed[$mime];
        $targetFs = $uploadDirFs . '/' . $filename;

        if (!move_uploaded_file($tmpName, $targetFs)) {
            return ['ok' => false, 'message' => 'Could not save uploaded logo.'];
        }

        return ['ok' => true, 'path' => $uploadDirWeb . '/' . $filename];
    }
}

ensure_lodge_settings_table($pdo);
ensure_lodge_settings_columns($pdo);

$settings = fetch_lodge_settings($pdo);
$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (function_exists('verify_csrf')) {
        verify_csrf();
    }

    $form = [
        'lodge_name'           => trim((string)($_POST['lodge_name'] ?? '')),
        'legal_name'           => trim((string)($_POST['legal_name'] ?? '')),
        'tag_line'             => trim((string)($_POST['tag_line'] ?? '')),
        'email'                => trim((string)($_POST['email'] ?? '')),
        'phone'                => trim((string)($_POST['phone'] ?? '')),
        'alt_phone'            => trim((string)($_POST['alt_phone'] ?? '')),
        'website'              => trim((string)($_POST['website'] ?? '')),
        'address_line1'        => trim((string)($_POST['address_line1'] ?? '')),
        'address_line2'        => trim((string)($_POST['address_line2'] ?? '')),
        'city'                 => trim((string)($_POST['city'] ?? '')),
        'state_region'         => trim((string)($_POST['state_region'] ?? '')),
        'country'              => trim((string)($_POST['country'] ?? '')),
        'postal_code'          => trim((string)($_POST['postal_code'] ?? '')),
        'currency_code'        => strtoupper(trim((string)($_POST['currency_code'] ?? 'USD'))),
        'timezone_name'        => trim((string)($_POST['timezone_name'] ?? 'Africa/Harare')),
        'check_in_time'        => normalise_time_value((string)($_POST['check_in_time'] ?? '14:00'), '14:00:00'),
        'check_out_time'       => normalise_time_value((string)($_POST['check_out_time'] ?? '10:00'), '10:00:00'),
        'tax_name'             => trim((string)($_POST['tax_name'] ?? 'VAT')),
        'tax_percent'          => (string)number_format((float)($_POST['tax_percent'] ?? 0), 2, '.', ''),
        'vat_number'           => trim((string)($_POST['vat_number'] ?? '')),
        'tin_number'           => trim((string)($_POST['tin_number'] ?? '')),
        'company_reg_number'   => trim((string)($_POST['company_reg_number'] ?? '')),
        'invoice_prefix'       => strtoupper(trim((string)($_POST['invoice_prefix'] ?? 'INV'))),
        'receipt_prefix'       => strtoupper(trim((string)($_POST['receipt_prefix'] ?? 'RCT'))),
        'reservation_prefix'   => strtoupper(trim((string)($_POST['reservation_prefix'] ?? 'BK'))),
        'bank_name'            => trim((string)($_POST['bank_name'] ?? '')),
        'bank_account_name'    => trim((string)($_POST['bank_account_name'] ?? '')),
        'bank_account_no'      => trim((string)($_POST['bank_account_no'] ?? '')),
        'bank_branch'          => trim((string)($_POST['bank_branch'] ?? '')),
        'bank_swift'           => trim((string)($_POST['bank_swift'] ?? '')),
        'cancellation_policy'  => trim((string)($_POST['cancellation_policy'] ?? '')),
        'payment_terms'        => trim((string)($_POST['payment_terms'] ?? '')),
        'terms_and_conditions' => trim((string)($_POST['terms_and_conditions'] ?? '')),
        'invoice_footer'       => trim((string)($_POST['invoice_footer'] ?? '')),
        'logo_path'            => trim((string)($_POST['existing_logo_path'] ?? '')),
    ];

    if ($form['lodge_name'] === '') {
        $errors[] = 'Lodge name is required.';
    }

    if ($form['email'] !== '' && !filter_var($form['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address.';
    }

    if ($form['currency_code'] === '') {
        $errors[] = 'Currency code is required.';
    }

    if ($form['invoice_prefix'] === '') {
        $errors[] = 'Invoice prefix is required.';
    }

    if ($form['receipt_prefix'] === '') {
        $errors[] = 'Receipt prefix is required.';
    }

    if ($form['reservation_prefix'] === '') {
        $errors[] = 'Reservation prefix is required.';
    }

    $logoResult = save_uploaded_logo($_FILES['logo_file'] ?? []);
    if (!$logoResult['ok']) {
        $errors[] = $logoResult['message'];
    } elseif (!empty($logoResult['path'])) {
        $form['logo_path'] = $logoResult['path'];
    }

    if (!$errors) {
        $sql = "
            INSERT INTO lodge_settings (
                id, lodge_name, legal_name, tag_line, email, phone, alt_phone, website,
                address_line1, address_line2, city, state_region, country, postal_code,
                currency_code, timezone_name, check_in_time, check_out_time, tax_name, tax_percent, vat_number, tin_number, company_reg_number,
                invoice_prefix, receipt_prefix, reservation_prefix, logo_path,
                bank_name, bank_account_name, bank_account_no, bank_branch, bank_swift,
                cancellation_policy, payment_terms, terms_and_conditions, invoice_footer, updated_by
            ) VALUES (
                :id, :lodge_name, :legal_name, :tag_line, :email, :phone, :alt_phone, :website,
                :address_line1, :address_line2, :city, :state_region, :country, :postal_code,
                :currency_code, :timezone_name, :check_in_time, :check_out_time, :tax_name, :tax_percent, :vat_number, :tin_number, :company_reg_number,
                :invoice_prefix, :receipt_prefix, :reservation_prefix, :logo_path,
                :bank_name, :bank_account_name, :bank_account_no, :bank_branch, :bank_swift,
                :cancellation_policy, :payment_terms, :terms_and_conditions, :invoice_footer, :updated_by
            )
            ON DUPLICATE KEY UPDATE
                lodge_name = VALUES(lodge_name),
                legal_name = VALUES(legal_name),
                tag_line = VALUES(tag_line),
                email = VALUES(email),
                phone = VALUES(phone),
                alt_phone = VALUES(alt_phone),
                website = VALUES(website),
                address_line1 = VALUES(address_line1),
                address_line2 = VALUES(address_line2),
                city = VALUES(city),
                state_region = VALUES(state_region),
                country = VALUES(country),
                postal_code = VALUES(postal_code),
                currency_code = VALUES(currency_code),
                timezone_name = VALUES(timezone_name),
                check_in_time = VALUES(check_in_time),
                check_out_time = VALUES(check_out_time),
                tax_name = VALUES(tax_name),
                tax_percent = VALUES(tax_percent),
                vat_number = VALUES(vat_number),
                tin_number = VALUES(tin_number),
                company_reg_number = VALUES(company_reg_number),
                invoice_prefix = VALUES(invoice_prefix),
                receipt_prefix = VALUES(receipt_prefix),
                reservation_prefix = VALUES(reservation_prefix),
                logo_path = VALUES(logo_path),
                bank_name = VALUES(bank_name),
                bank_account_name = VALUES(bank_account_name),
                bank_account_no = VALUES(bank_account_no),
                bank_branch = VALUES(bank_branch),
                bank_swift = VALUES(bank_swift),
                cancellation_policy = VALUES(cancellation_policy),
                payment_terms = VALUES(payment_terms),
                terms_and_conditions = VALUES(terms_and_conditions),
                invoice_footer = VALUES(invoice_footer),
                updated_by = VALUES(updated_by)
        ";

        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':id'                  => (int)($settings['id'] ?? 1) > 0 ? (int)$settings['id'] : 1,
            ':lodge_name'          => $form['lodge_name'],
            ':legal_name'          => $form['legal_name'] !== '' ? $form['legal_name'] : null,
            ':tag_line'            => $form['tag_line'] !== '' ? $form['tag_line'] : null,
            ':email'               => $form['email'] !== '' ? $form['email'] : null,
            ':phone'               => $form['phone'] !== '' ? $form['phone'] : null,
            ':alt_phone'           => $form['alt_phone'] !== '' ? $form['alt_phone'] : null,
            ':website'             => $form['website'] !== '' ? $form['website'] : null,
            ':address_line1'       => $form['address_line1'] !== '' ? $form['address_line1'] : null,
            ':address_line2'       => $form['address_line2'] !== '' ? $form['address_line2'] : null,
            ':city'                => $form['city'] !== '' ? $form['city'] : null,
            ':state_region'        => $form['state_region'] !== '' ? $form['state_region'] : null,
            ':country'             => $form['country'] !== '' ? $form['country'] : null,
            ':postal_code'         => $form['postal_code'] !== '' ? $form['postal_code'] : null,
            ':currency_code'       => $form['currency_code'],
            ':timezone_name'       => $form['timezone_name'],
            ':check_in_time'       => $form['check_in_time'],
            ':check_out_time'      => $form['check_out_time'],
            ':tax_name'            => $form['tax_name'] !== '' ? $form['tax_name'] : null,
            ':tax_percent'         => $form['tax_percent'],
            ':vat_number'          => $form['vat_number'] !== '' ? $form['vat_number'] : null,
            ':tin_number'          => $form['tin_number'] !== '' ? $form['tin_number'] : null,
            ':company_reg_number'  => $form['company_reg_number'] !== '' ? $form['company_reg_number'] : null,
            ':invoice_prefix'      => $form['invoice_prefix'],
            ':receipt_prefix'      => $form['receipt_prefix'],
            ':reservation_prefix'  => $form['reservation_prefix'],
            ':logo_path'           => $form['logo_path'] !== '' ? $form['logo_path'] : null,
            ':bank_name'           => $form['bank_name'] !== '' ? $form['bank_name'] : null,
            ':bank_account_name'   => $form['bank_account_name'] !== '' ? $form['bank_account_name'] : null,
            ':bank_account_no'     => $form['bank_account_no'] !== '' ? $form['bank_account_no'] : null,
            ':bank_branch'         => $form['bank_branch'] !== '' ? $form['bank_branch'] : null,
            ':bank_swift'          => $form['bank_swift'] !== '' ? $form['bank_swift'] : null,
            ':cancellation_policy' => $form['cancellation_policy'] !== '' ? $form['cancellation_policy'] : null,
            ':payment_terms'       => $form['payment_terms'] !== '' ? $form['payment_terms'] : null,
            ':terms_and_conditions'=> $form['terms_and_conditions'] !== '' ? $form['terms_and_conditions'] : null,
            ':invoice_footer'      => $form['invoice_footer'] !== '' ? $form['invoice_footer'] : null,
            ':updated_by'          => (int)($_SESSION['user_id'] ?? 0) ?: null,
        ]);

        $success = 'Lodge settings saved successfully.';
        $settings = fetch_lodge_settings($pdo);
    } else {
        $settings = array_merge($settings, $form);
    }
}

require_once __DIR__ . '/../../includes/header.php';
?>
<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50">
                <i class="bi bi-gear-wide-connected"></i> Setup
            </div>
            <div class="hero-title mt-2">Lodge Settings</div>
            <div class="hero-subtitle mt-2">
                Control the lodge identity, contact details, invoice defaults, timing rules, and operational notes used across the PMS.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="/rooms/" class="btn btn-outline-light">
                <i class="bi bi-arrow-left me-2"></i>Back to Dashboard
            </a>
        </div>
    </div>
</div>

<?php
if ($success !== '') {
    echo settings_alert($success, 'success');
}
if ($errors) {
    echo '<div class="alert alert-danger"><div class="fw-bold mb-2">Please fix the following:</div><ul class="mb-0">';
    foreach ($errors as $error) {
        echo '<li>' . h($error) . '</li>';
    }
    echo '</ul></div>';
}
?>

<form method="post" enctype="multipart/form-data" class="row g-2 align-items-start">
    <?php if (function_exists('csrf_token')): ?>
        <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
    <?php endif; ?>

    <div class="col-xl-8">
        <div class="form-section compact-card mb-2">
            <div class="form-section-title">
                <i class="bi bi-building"></i> Lodge Identity
            </div>

            <div class="row g-2">
                <div class="col-md-6">
                    <label class="form-label">Lodge Name</label>
                    <input type="text" name="lodge_name" class="form-control" value="<?php echo h($settings['lodge_name'] ?? ''); ?>" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Legal Name</label>
                    <input type="text" name="legal_name" class="form-control" value="<?php echo h($settings['legal_name'] ?? ''); ?>">
                </div>

                <div class="col-md-12">
                    <label class="form-label">Tag Line or Motto</label>
                    <input type="text" name="tag_line" class="form-control" value="<?php echo h($settings['tag_line'] ?? ''); ?>">
                </div>

                <div class="col-md-4">
                    <label class="form-label">Email</label>
                    <input type="email" name="email" class="form-control" value="<?php echo h($settings['email'] ?? ''); ?>">
                </div>

                <div class="col-md-4">
                    <label class="form-label">Phone</label>
                    <input type="text" name="phone" class="form-control" value="<?php echo h($settings['phone'] ?? ''); ?>">
                </div>

                <div class="col-md-4">
                    <label class="form-label">Alternative Phone</label>
                    <input type="text" name="alt_phone" class="form-control" value="<?php echo h($settings['alt_phone'] ?? ''); ?>">
                </div>

                <div class="col-md-12">
                    <label class="form-label">Website</label>
                    <input type="text" name="website" class="form-control" value="<?php echo h($settings['website'] ?? ''); ?>" placeholder="https://...">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Address Line 1</label>
                    <input type="text" name="address_line1" class="form-control" value="<?php echo h($settings['address_line1'] ?? ''); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Address Line 2</label>
                    <input type="text" name="address_line2" class="form-control" value="<?php echo h($settings['address_line2'] ?? ''); ?>">
                </div>

                <div class="col-md-3">
                    <label class="form-label">City</label>
                    <input type="text" name="city" class="form-control" value="<?php echo h($settings['city'] ?? ''); ?>">
                </div>

                <div class="col-md-3">
                    <label class="form-label">State / Region</label>
                    <input type="text" name="state_region" class="form-control" value="<?php echo h($settings['state_region'] ?? ''); ?>">
                </div>

                <div class="col-md-3">
                    <label class="form-label">Country</label>
                    <input type="text" name="country" class="form-control" value="<?php echo h($settings['country'] ?? ''); ?>">
                </div>

                <div class="col-md-3">
                    <label class="form-label">Postal Code</label>
                    <input type="text" name="postal_code" class="form-control" value="<?php echo h($settings['postal_code'] ?? ''); ?>">
                </div>
            </div>
        </div>

        <div class="form-section compact-card mb-2">
            <div class="form-section-title">
                <i class="bi bi-clock-history"></i> Operations & Billing
            </div>

            <div class="row g-2">
                <div class="col-md-3">
                    <label class="form-label">Currency</label>
                    <input type="text" name="currency_code" class="form-control" maxlength="10" value="<?php echo h($settings['currency_code'] ?? 'USD'); ?>">
                </div>

                <div class="col-md-5">
                    <label class="form-label">Timezone</label>
                    <input type="text" name="timezone_name" class="form-control" value="<?php echo h($settings['timezone_name'] ?? 'Africa/Harare'); ?>">
                </div>

                <div class="col-md-2">
                    <label class="form-label">Check In</label>
                    <input type="time" name="check_in_time" class="form-control" value="<?php echo h(substr((string)($settings['check_in_time'] ?? '14:00:00'), 0, 5)); ?>">
                </div>

                <div class="col-md-2">
                    <label class="form-label">Check Out</label>
                    <input type="time" name="check_out_time" class="form-control" value="<?php echo h(substr((string)($settings['check_out_time'] ?? '10:00:00'), 0, 5)); ?>">
                </div>

                <div class="col-md-3">
                    <label class="form-label">Tax Name</label>
                    <input type="text" name="tax_name" class="form-control" value="<?php echo h($settings['tax_name'] ?? 'VAT'); ?>">
                </div>

                <div class="col-md-3">
                    <label class="form-label">Tax %</label>
                    <input type="number" step="0.01" min="0" name="tax_percent" class="form-control" value="<?php echo h($settings['tax_percent'] ?? '0.00'); ?>">
                </div>

                <div class="col-md-4">
                    <label class="form-label">VAT Number</label>
                    <input type="text" name="vat_number" class="form-control" value="<?php echo h($settings['vat_number'] ?? ''); ?>" placeholder="VAT registration number">
                </div>

                <div class="col-md-4">
                    <label class="form-label">TIN Number</label>
                    <input type="text" name="tin_number" class="form-control" value="<?php echo h($settings['tin_number'] ?? ''); ?>" placeholder="Tax identification number">
                </div>

                <div class="col-md-4">
                    <label class="form-label">Company Reg. Number</label>
                    <input type="text" name="company_reg_number" class="form-control" value="<?php echo h($settings['company_reg_number'] ?? ''); ?>" placeholder="Company registration number">
                </div>

                <div class="col-md-2">
                    <label class="form-label">Invoice Prefix</label>
                    <input type="text" name="invoice_prefix" class="form-control" maxlength="20" value="<?php echo h($settings['invoice_prefix'] ?? 'INV'); ?>">
                </div>

                <div class="col-md-2">
                    <label class="form-label">Receipt Prefix</label>
                    <input type="text" name="receipt_prefix" class="form-control" maxlength="20" value="<?php echo h($settings['receipt_prefix'] ?? 'RCT'); ?>">
                </div>

                <div class="col-md-2">
                    <label class="form-label">Reservation Prefix</label>
                    <input type="text" name="reservation_prefix" class="form-control" maxlength="20" value="<?php echo h($settings['reservation_prefix'] ?? 'BK'); ?>">
                </div>
            </div>
        </div>

        <div class="form-section compact-card">
            <div class="form-section-title">
                <i class="bi bi-file-text"></i> Policies & Footer Text
            </div>

            <div class="row g-2">
                <div class="col-12">
                    <label class="form-label">Cancellation Policy</label>
                    <textarea name="cancellation_policy" class="form-control" rows="2"><?php echo h($settings['cancellation_policy'] ?? ''); ?></textarea>
                </div>

                <div class="col-12">
                    <label class="form-label">Payment Terms</label>
                    <textarea name="payment_terms" class="form-control" rows="2"><?php echo h($settings['payment_terms'] ?? ''); ?></textarea>
                </div>

                <div class="col-12">
                    <label class="form-label">Terms & Conditions</label>
                    <textarea name="terms_and_conditions" class="form-control" rows="3"><?php echo h($settings['terms_and_conditions'] ?? ''); ?></textarea>
                </div>

                <div class="col-12">
                    <label class="form-label">Invoice Footer</label>
                    <textarea name="invoice_footer" class="form-control" rows="2"><?php echo h($settings['invoice_footer'] ?? ''); ?></textarea>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-4">
        <div class="form-section compact-card mb-2">
            <div class="form-section-title">
                <i class="bi bi-image"></i> Branding
            </div>

            <input type="hidden" name="existing_logo_path" value="<?php echo h($settings['logo_path'] ?? ''); ?>">

            <?php if (!empty($settings['logo_path'])): ?>
                <div class="mb-2 text-center compact-logo-box">
                    <img src="<?php echo h($settings['logo_path']); ?>" alt="Lodge logo" style="max-width: 100%; max-height: 64px; object-fit: contain;">
                </div>
            <?php else: ?>
                <div class="text-muted small mb-3">No logo uploaded yet.</div>
            <?php endif; ?>

            <div class="mb-2">
                <label class="form-label">Upload Logo</label>
                <input type="file" name="logo_file" class="form-control" accept=".jpg,.jpeg,.png,.gif,.webp">
            </div>

            <div class="small text-muted compact-help">PNG/JPG for documents.</div>
        </div>

        <div class="form-section compact-card mb-2">
            <div class="form-section-title">
                <i class="bi bi-bank"></i> Banking
            </div>

            <div class="row g-2">
                <div class="col-12">
                    <label class="form-label">Bank Name</label>
                    <input type="text" name="bank_name" class="form-control" value="<?php echo h($settings['bank_name'] ?? ''); ?>">
                </div>

                <div class="col-12">
                    <label class="form-label">Account Name</label>
                    <input type="text" name="bank_account_name" class="form-control" value="<?php echo h($settings['bank_account_name'] ?? ''); ?>">
                </div>

                <div class="col-12">
                    <label class="form-label">Account Number</label>
                    <input type="text" name="bank_account_no" class="form-control" value="<?php echo h($settings['bank_account_no'] ?? ''); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Branch</label>
                    <input type="text" name="bank_branch" class="form-control" value="<?php echo h($settings['bank_branch'] ?? ''); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">SWIFT</label>
                    <input type="text" name="bank_swift" class="form-control" value="<?php echo h($settings['bank_swift'] ?? ''); ?>">
                </div>
            </div>
        </div>

        <div class="form-section compact-card">
            <div class="form-section-title">
                <i class="bi bi-check2-square"></i> Save
            </div>

            <div class="mini-stat mb-1">
                <span>Default Currency</span>
                <strong><?php echo h($settings['currency_code'] ?? 'USD'); ?></strong>
            </div>

            <div class="mini-stat mb-1">
                <span>Check In / Out</span>
                <strong>
                    <?php echo h(substr((string)($settings['check_in_time'] ?? '14:00:00'), 0, 5)); ?>
                    /
                    <?php echo h(substr((string)($settings['check_out_time'] ?? '10:00:00'), 0, 5)); ?>
                </strong>
            </div>

            <div class="d-grid gap-2 mt-2">
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="bi bi-save me-2"></i>Save Lodge Settings
                </button>
                <a href="/rooms/" class="btn btn-light">Cancel</a>
            </div>
        </div>
    </div>
</form>


<style>
    .hero-band{
        padding:18px 22px !important;
        margin-bottom:14px !important;
        border-radius:18px !important;
    }
    .hero-band .row{
        --bs-gutter-y:.75rem;
    }
    .hero-title{
        font-size:1.45rem !important;
        line-height:1.15 !important;
        margin-top:4px !important;
    }
    .hero-subtitle{
        font-size:.9rem !important;
        margin-top:4px !important;
        max-width:760px;
    }
    .page-eyebrow{
        font-size:.76rem !important;
        letter-spacing:.08em;
        text-transform:uppercase;
    }
    .form-section{
        padding:14px 16px !important;
        margin-bottom:14px !important;
        border-radius:16px !important;
    }
    .form-section-title{
        margin-bottom:10px !important;
        font-size:.92rem !important;
    }
    .row.g-3{
        --bs-gutter-y:.65rem;
    }
    .form-label{
        margin-bottom:3px !important;
        font-size:.8rem;
        font-weight:700;
        color:#475569;
    }
    .form-control,
    .form-select{
        padding:.42rem .65rem !important;
        min-height:36px;
    }
    textarea.form-control{
        min-height:auto;
    }
    .mini-stat{
        padding:7px 0 !important;
        margin-bottom:8px !important;
    }
    .btn-lg{
        padding:.55rem .9rem !important;
        font-size:.98rem !important;
    }
</style>


<style>
    /* Ultra compact override: remove inherited large card heights/gaps */
    .hero-band{
        padding:10px 14px !important;
        margin-bottom:8px !important;
        border-radius:14px !important;
        min-height:0 !important;
    }
    .hero-band .row{--bs-gutter-y:.25rem !important;}
    .page-eyebrow{font-size:.68rem !important; line-height:1 !important; margin:0 !important;}
    .hero-title{font-size:1.15rem !important; line-height:1.05 !important; margin:2px 0 0 !important;}
    .hero-subtitle{font-size:.76rem !important; line-height:1.15 !important; margin:2px 0 0 !important; max-width:720px;}
    .hero-band .btn{padding:.32rem .6rem !important; font-size:.8rem !important;}

    form.row{--bs-gutter-x:.6rem !important; --bs-gutter-y:.55rem !important;}
    .compact-card,
    .form-section{
        height:auto !important;
        min-height:0 !important;
        padding:8px 10px !important;
        margin-bottom:8px !important;
        border-radius:12px !important;
        box-shadow:0 4px 14px rgba(15,23,42,.04) !important;
    }
    .form-section-title{
        margin-bottom:5px !important;
        padding-bottom:4px !important;
        font-size:.78rem !important;
        line-height:1.05 !important;
    }
    .row.g-2{--bs-gutter-x:.45rem !important; --bs-gutter-y:.38rem !important;}
    .form-label{
        margin-bottom:1px !important;
        font-size:.68rem !important;
        line-height:1.05 !important;
        font-weight:700 !important;
    }
    .form-control,
    .form-select{
        padding:.24rem .45rem !important;
        min-height:28px !important;
        height:28px !important;
        font-size:.78rem !important;
        line-height:1.1 !important;
        border-radius:7px !important;
    }
    textarea.form-control{
        height:auto !important;
        min-height:46px !important;
        padding:.3rem .45rem !important;
    }
    textarea[name="terms_and_conditions"]{min-height:58px !important;}
    .compact-logo-box{margin-bottom:4px !important;}
    .compact-logo-box img{max-height:54px !important;}
    .compact-help{font-size:.68rem !important; line-height:1.1 !important; margin-top:2px !important;}
    .mini-stat{
        padding:3px 0 !important;
        margin-bottom:3px !important;
        min-height:0 !important;
        line-height:1.05 !important;
    }
    .mini-stat span,
    .mini-stat strong{font-size:.74rem !important;}
    .btn-lg{padding:.38rem .7rem !important; font-size:.84rem !important;}
    .alert{padding:.45rem .65rem !important; margin-bottom:.5rem !important;}

    /* keep right column cards from visually stretching */
    .col-xl-4 .form-section{padding-top:7px !important; padding-bottom:7px !important;}
    .col-xl-4 .form-section-title{margin-bottom:4px !important;}
</style>

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