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

require_login('admin');
$page_title = 'Approval Tenant - ANATL Portal';

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

    $app_id = intval($_POST['app_id'] ?? 0);
    $action = $_POST['action'] ?? '';
    $admin_notes = trim($_POST['admin_notes'] ?? '');

    if ($app_id && in_array($action, ['review', 'site_visit', 'approved', 'rejected', 'contract'])) {
        $stmt = $conn->prepare('UPDATE rental_applications SET status = ?, admin_notes = ?, updated_at = NOW() WHERE id = ?');
        $stmt->bind_param('ssi', $action, $admin_notes, $app_id);
        $stmt->execute();
        $stmt->close();
        set_flash('success', 'Status pengajuan berhasil diubah');
    }

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

$apps = [];
$result = $conn->query('
    SELECT ra.*, u.company_name, u.email, ru.name as unit_name
    FROM rental_applications ra
    JOIN users u ON ra.user_id = u.id
    JOIN rental_units ru ON ra.unit_id = ru.id
    WHERE ra.status IN ("submitted", "review", "site_visit")
    ORDER BY ra.created_at DESC
');
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $apps[] = $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">👥 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 sidebar-item--active">🏢 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;">Approval Pengajuan Tenant</h1>

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

            <?php if (empty($apps)): ?>
            <div class="empty-state">
                <div class="empty-state__icon">✅</div>
                <div class="empty-state__message">Semua pengajuan tenant telah diproses</div>
            </div>
            <?php else: ?>

            <?php foreach ($apps as $app): ?>
            <div class="card" style="margin-bottom: 24px;">
                <div class="card__header">
                    <div>
                        <div class="card__title"><?= esc($app['business_name']) ?></div>
                        <p style="color: #5A6A7A; font-size: 14px; margin-top: 4px;">
                            Unit: <?= esc($app['unit_name']) ?> • Durasi: <?= $app['duration_months'] ?> bulan
                        </p>
                    </div>
                    <span class="badge badge--<?= esc($app['status']) ?>">
                        <?= esc(ucfirst(str_replace('_', ' ', $app['status']))) ?>
                    </span>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px;">
                    <div>
                        <p style="color: #5A6A7A; font-size: 12px;">Tipe Bisnis</p>
                        <p style="font-weight: 600;"><?= esc($app['business_type'] ?? '-') ?></p>
                    </div>
                    <div>
                        <p style="color: #5A6A7A; font-size: 12px;">Email</p>
                        <p style="font-weight: 600;"><?= esc($app['email']) ?></p>
                    </div>
                </div>

                <form method="POST" style="display: grid; grid-template-columns: 1fr; gap: 16px;">
                    <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                    <input type="hidden" name="app_id" value="<?= $app['id'] ?>">

                    <div class="form-group">
                        <label for="notes_<?= $app['id'] ?>">Catatan</label>
                        <textarea id="notes_<?= $app['id'] ?>" name="admin_notes" placeholder="Catatan untuk pemohon..."></textarea>
                    </div>

                    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px;">
                        <button type="submit" name="action" value="review" class="btn btn--secondary btn--small">Review</button>
                        <button type="submit" name="action" value="site_visit" class="btn btn--secondary btn--small">Site Visit</button>
                        <button type="submit" name="action" value="approved" class="btn btn--success btn--small">Setujui</button>
                        <button type="submit" name="action" value="rejected" class="btn btn--danger btn--small">Tolak</button>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>

            <?php endif; ?>
        </div>
    </div>
</div>

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