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

$pageTitle = 'Nationality Setup';

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

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

$errors = [];
$success = '';

$hasIsActive = table_has_column_nat($pdo, 'nationality', 'is_active');
$hasCreatedAt = table_has_column_nat($pdo, 'nationality', 'created_at');
$hasUpdatedAt = table_has_column_nat($pdo, 'nationality', 'updated_at');

$action = trim((string)($_GET['action'] ?? ''));
$editId = (int)($_GET['id'] ?? 0);
$editRow = null;

if (isset($_GET['saved']) && (int)$_GET['saved'] === 1) {
    $success = 'Nationality saved successfully.';
}
if (isset($_GET['deleted']) && (int)$_GET['deleted'] === 1) {
    $success = 'Nationality removed successfully.';
}
if (isset($_GET['status']) && $_GET['status'] === 'updated') {
    $success = 'Nationality status updated successfully.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction = trim((string)($_POST['form_action'] ?? 'save'));
    $id = (int)($_POST['id'] ?? 0);
    $nationalityName = trim((string)($_POST['nationality'] ?? ''));

    if ($postAction === 'delete') {
        if ($id <= 0) {
            $errors[] = 'Invalid nationality selected.';
        }

        if (!$errors) {
            try {
                $stmt = $pdo->prepare("DELETE FROM nationality WHERE id = :id LIMIT 1");
                $stmt->execute([':id' => $id]);
                header('Location: nationality.php?deleted=1');
                exit;
            } catch (Throwable $e) {
                $errors[] = 'Could not delete nationality. It may already be used on guest registrations.';
            }
        }
    } elseif ($postAction === 'toggle_status') {
        if (!$hasIsActive) {
            $errors[] = 'Status control needs an is_active column on nationality table.';
        }
        if ($id <= 0) {
            $errors[] = 'Invalid nationality selected.';
        }

        if (!$errors) {
            try {
                $stmt = $pdo->prepare("\n                    UPDATE nationality\n                    SET is_active = CASE WHEN COALESCE(is_active,1) = 1 THEN 0 ELSE 1 END\n                    " . ($hasUpdatedAt ? ", updated_at = NOW()" : "") . "\n                    WHERE id = :id\n                ");
                $stmt->execute([':id' => $id]);
                header('Location: nationality.php?status=updated');
                exit;
            } catch (Throwable $e) {
                $errors[] = $e->getMessage();
            }
        }
    } else {
        if ($nationalityName === '') {
            $errors[] = 'Nationality name is required.';
        }

        if (!$errors) {
            try {
                $stmt = $pdo->prepare("\n                    SELECT id\n                    FROM nationality\n                    WHERE LOWER(nationality) = LOWER(:nationality)\n                      AND id <> :id\n                    LIMIT 1\n                ");
                $stmt->execute([
                    ':nationality' => $nationalityName,
                    ':id'          => $id,
                ]);
                if ((int)$stmt->fetchColumn() > 0) {
                    $errors[] = 'This nationality already exists.';
                }
            } catch (Throwable $e) {
                $errors[] = $e->getMessage();
            }
        }

        if (!$errors) {
            try {
                if ($id > 0) {
                    $sql = "\n                        UPDATE nationality\n                        SET nationality = :nationality\n                    ";
                    if ($hasUpdatedAt) {
                        $sql .= ", updated_at = NOW() ";
                    }
                    $sql .= " WHERE id = :id ";

                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        ':nationality' => $nationalityName,
                        ':id'          => $id,
                    ]);
                } else {
                    $columns = ['nationality'];
                    $values = [':nationality'];
                    $params = [':nationality' => $nationalityName];

                    if ($hasIsActive) {
                        $columns[] = 'is_active';
                        $values[] = '1';
                    }
                    if ($hasCreatedAt) {
                        $columns[] = 'created_at';
                        $values[] = 'NOW()';
                    }
                    if ($hasUpdatedAt) {
                        $columns[] = 'updated_at';
                        $values[] = 'NOW()';
                    }

                    $sql = "INSERT INTO nationality (" . implode(',', $columns) . ") VALUES (" . implode(',', $values) . ")";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                }

                header('Location: nationality.php?saved=1');
                exit;
            } catch (Throwable $e) {
                $errors[] = $e->getMessage();
            }
        }
    }
}

if ($action === 'edit' && $editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM nationality WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $editId]);
    $editRow = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

$search = trim((string)($_GET['q'] ?? ''));
$sql = "SELECT * FROM nationality WHERE 1=1";
$params = [];
if ($search !== '') {
    $sql .= " AND nationality LIKE :q";
    $params[':q'] = '%' . $search . '%';
}
$sql .= " ORDER BY nationality ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<div class="hero-band mb-4">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-globe2"></i> Guest Master Data</div>
            <div class="hero-title mt-2">Nationality Setup</div>
            <div class="hero-subtitle mt-2">
                Maintain the nationality dropdown used on guest registration during check-in.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="/rooms/modules/payments/checkin.php" class="btn btn-outline-light">
                <i class="bi bi-door-open me-2"></i>Back to Check-In
            </a>
        </div>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success"><?php echo h($success); ?></div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (!$hasIsActive): ?>
    <div class="alert alert-warning">
        Optional: add <code>is_active</code> if you want to deactivate nationalities instead of deleting them.
    </div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm setup-card">
            <div class="card-header bg-white border-0 pt-4 px-4">
                <h5 class="mb-1"><?php echo $editRow ? 'Edit Nationality' : 'Add Nationality'; ?></h5>
                <div class="text-muted small">This list appears in the check-in guest registration form.</div>
            </div>
            <div class="card-body p-4">
                <form method="post">
                    <input type="hidden" name="form_action" value="save">
                    <input type="hidden" name="id" value="<?php echo (int)($editRow['id'] ?? 0); ?>">

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nationality</label>
                        <input type="text"
                               name="nationality"
                               class="form-control form-control-lg"
                               value="<?php echo h($editRow['nationality'] ?? ''); ?>"
                               placeholder="Example: Zimbabwean"
                               required>
                    </div>

                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="bi bi-save me-2"></i><?php echo $editRow ? 'Update Nationality' : 'Save Nationality'; ?>
                        </button>
                        <?php if ($editRow): ?>
                            <a href="nationality.php" class="btn btn-light border">Cancel Edit</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card border-0 shadow-sm setup-card">
            <div class="card-header bg-white border-0 pt-4 px-4">
                <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
                    <div>
                        <h5 class="mb-1">Nationality List</h5>
                        <div class="text-muted small"><?php echo count($rows); ?> record(s) found</div>
                    </div>
                    <form method="get" class="d-flex gap-2">
                        <input type="search" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="Search nationality...">
                        <button class="btn btn-outline-primary"><i class="bi bi-search"></i></button>
                        <?php if ($search !== ''): ?>
                            <a href="nationality.php" class="btn btn-outline-secondary">Reset</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th style="width:80px;">#</th>
                                <th>Nationality</th>
                                <?php if ($hasIsActive): ?>
                                    <th>Status</th>
                                <?php endif; ?>
                                <th class="text-end" style="width:260px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$rows): ?>
                                <tr>
                                    <td colspan="<?php echo $hasIsActive ? 4 : 3; ?>" class="text-center text-muted py-5">
                                        No nationalities found.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($rows as $index => $row): ?>
                                    <?php $active = !$hasIsActive || (int)($row['is_active'] ?? 1) === 1; ?>
                                    <tr>
                                        <td class="text-muted"><?php echo $index + 1; ?></td>
                                        <td>
                                            <div class="fw-bold"><?php echo h($row['nationality']); ?></div>
                                            <div class="small text-muted">ID: <?php echo (int)$row['id']; ?></div>
                                        </td>
                                        <?php if ($hasIsActive): ?>
                                            <td>
                                                <?php if ($active): ?>
                                                    <span class="badge text-bg-success">Active</span>
                                                <?php else: ?>
                                                    <span class="badge text-bg-secondary">Inactive</span>
                                                <?php endif; ?>
                                            </td>
                                        <?php endif; ?>
                                        <td class="text-end">
                                            <div class="d-flex justify-content-end gap-2">
                                                <a href="nationality.php?action=edit&id=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                    <i class="bi bi-pencil-square me-1"></i>Edit
                                                </a>

                                                <?php if ($hasIsActive): ?>
                                                    <form method="post" class="d-inline">
                                                        <input type="hidden" name="form_action" value="toggle_status">
                                                        <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                        <button type="submit" class="btn btn-sm btn-outline-secondary">
                                                            <?php echo $active ? 'Deactivate' : 'Activate'; ?>
                                                        </button>
                                                    </form>
                                                <?php endif; ?>

                                                <form method="post" class="d-inline" onsubmit="return confirm('Delete this nationality? If it is already used, deletion may fail.');">
                                                    <input type="hidden" name="form_action" value="delete">
                                                    <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                                        <i class="bi bi-trash me-1"></i>Delete
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.setup-card{
    border-radius:22px;
    overflow:hidden;
}
.hero-band{
    border-radius:24px;
    padding:28px;
    background:linear-gradient(135deg,#0f172a 0%,#1d4ed8 100%);
    color:#fff;
    box-shadow:0 18px 40px rgba(15,23,42,.16);
}
.hero-title{
    font-size:2rem;
    font-weight:800;
    letter-spacing:-.03em;
}
.hero-subtitle{
    max-width:760px;
    color:rgba(255,255,255,.78);
}
.page-eyebrow{
    text-transform:uppercase;
    letter-spacing:.08em;
    font-size:.75rem;
    font-weight:800;
}
</style>

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