<?php
require_once '../includes/auth.php';
require_once '../includes/functions.php';

require_login('admin');
$page_title = 'Kelola User - ANATL Portal';

// Handle user actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validate_csrf($_POST['csrf_token'] ?? '')) {
        die('Invalid request');
    }

    $action = $_POST['action'] ?? '';
    $user_id = intval($_POST['user_id'] ?? 0);

    if ($action === 'toggle_active' && $user_id) {
        $stmt = $conn->prepare('UPDATE users SET is_active = NOT is_active WHERE id = ?');
        $stmt->bind_param('i', $user_id);
        $stmt->execute();
        $stmt->close();
        set_flash('success', 'Status user berhasil diubah');
    } elseif ($action === 'add_user') {
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $role = trim($_POST['role'] ?? '');
        $company_name = trim($_POST['company_name'] ?? '');

        if ($username && $email && $password && $role) {
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare('INSERT INTO users (username, email, password_hash, role, company_name) VALUES (?, ?, ?, ?, ?)');
            $stmt->bind_param('sssss', $username, $email, $password_hash, $role, $company_name);

            if ($stmt->execute()) {
                set_flash('success', 'User berhasil ditambahkan');
            } else {
                set_flash('error', 'Email atau username sudah terdaftar');
            }
            $stmt->close();
        } else {
            set_flash('error', 'Semua field harus diisi');
        }
    }

    header('Location: ' . BASE_URL . '/admin/users.php');
    exit;
}

// Get all users
$users = [];
$result = $conn->query('SELECT * FROM users ORDER BY created_at DESC');
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $users[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?></title>
    <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css">
</head>
<body>
<?php require '../includes/header.php'; ?>

<div class="main">
    <div class="portal">
        <div class="portal__sidebar">
            <div class="sidebar__title">Menu Admin</div>
            <a href="<?= BASE_URL ?>/admin/index.php" class="sidebar-item">📊 Dashboard</a>
            <a href="<?= BASE_URL ?>/admin/users.php" class="sidebar-item sidebar-item--active">👥 Kelola User</a>
            <a href="<?= BASE_URL ?>/admin/slot.php" class="sidebar-item">✈️ Slot Time</a>
            <a href="<?= BASE_URL ?>/admin/flight-plan.php" class="sidebar-item">📋 Flight Plan</a>
            <a href="<?= BASE_URL ?>/admin/tenant.php" class="sidebar-item">🏢 Tenant</a>
            <a href="<?= BASE_URL ?>/admin/ground-handling.php" class="sidebar-item">🚗 Ground Handler</a>
            <a href="<?= BASE_URL ?>/admin/cms.php" class="sidebar-item">📰 CMS</a>
        </div>

        <div class="portal__content">
            <h1 style="color: #003A70; margin-bottom: 32px;">Kelola User</h1>

            <?php if ($flash = get_flash()): ?>
            <div class="alert alert--<?= esc($flash['type']) ?>">
                <?= esc($flash['msg']) ?>
            </div>
            <?php endif; ?>

            <div class="card" style="margin-bottom: 48px;">
                <div class="card__header">
                    <div class="card__title">Tambah User Baru</div>
                </div>
                <form method="POST" class="form">
                    <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                    <input type="hidden" name="action" value="add_user">

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group">
                            <label for="username">Username</label>
                            <input type="text" id="username" name="username" required>
                        </div>
                        <div class="form-group">
                            <label for="email">Email</label>
                            <input type="email" id="email" name="email" required>
                        </div>
                        <div class="form-group">
                            <label for="password">Password</label>
                            <input type="password" id="password" name="password" required>
                        </div>
                        <div class="form-group">
                            <label for="role">Role</label>
                            <select id="role" name="role" required>
                                <option value="">-- Pilih Role --</option>
                                <option value="admin">Admin</option>
                                <option value="airline">Airline</option>
                                <option value="customs">Customs</option>
                                <option value="ground_handler">Ground Handler</option>
                                <option value="tenant">Tenant</option>
                            </select>
                        </div>
                        <div class="form-group" style="grid-column: 1 / -1;">
                            <label for="company_name">Nama Perusahaan</label>
                            <input type="text" id="company_name" name="company_name">
                        </div>
                        <button type="submit" class="btn btn--success" style="grid-column: 1 / -1;">Tambah User</button>
                    </div>
                </form>
            </div>

            <div class="card">
                <div class="card__header">
                    <div class="card__title">Daftar User</div>
                </div>

                <div style="overflow-x: auto;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Username</th>
                                <th>Email</th>
                                <th>Role</th>
                                <th>Perusahaan</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($users as $user): ?>
                            <tr>
                                <td><?= esc($user['username']) ?></td>
                                <td><?= esc($user['email']) ?></td>
                                <td><span class="badge badge--submitted"><?= esc($user['role']) ?></span></td>
                                <td><?= esc($user['company_name'] ?? '-') ?></td>
                                <td>
                                    <?php if ($user['is_active']): ?>
                                        <span class="badge badge--approved">Aktif</span>
                                    <?php else: ?>
                                        <span class="badge badge--rejected">Nonaktif</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                                        <input type="hidden" name="action" value="toggle_active">
                                        <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                        <button type="submit" class="btn btn--small btn--secondary">
                                            <?= $user['is_active'] ? 'Nonaktifkan' : 'Aktifkan' ?>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require '../includes/footer.php'; ?>
