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

require_login('tenant');
$page_title = 'Pengajuan Sewa - ANATL Portal';
$user_id = $_SESSION['user_id'];

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

    $unit_id = intval($_POST['unit_id'] ?? 0);
    $business_name = trim($_POST['business_name'] ?? '');
    $business_type = trim($_POST['business_type'] ?? '');
    $duration_months = intval($_POST['duration_months'] ?? 0);

    if ($unit_id && $business_name && $duration_months) {
        $doc_path = handle_upload('doc', 'tenant-docs');

        $stmt = $conn->prepare('INSERT INTO rental_applications (user_id, unit_id, business_name, business_type, duration_months, doc_path) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->bind_param('iissis', $user_id, $unit_id, $business_name, $business_type, $duration_months, $doc_path);

        if ($stmt->execute()) {
            set_flash('success', 'Pengajuan sewa berhasil dikirim');
        } else {
            set_flash('error', 'Gagal mengirim pengajuan');
        }
        $stmt->close();
    } else {
        set_flash('error', 'Semua field harus diisi');
    }

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

// Get units
$units = [];
$result = $conn->query('SELECT * FROM rental_units WHERE is_available = 1');
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $units[] = $row;
    }
}

// Get user's applications
$apps = [];
$result = $conn->query("SELECT ra.*, ru.name as unit_name FROM rental_applications ra JOIN rental_units ru ON ra.unit_id = ru.id WHERE ra.user_id = $user_id 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 Tenant</div>
            <a href="<?= BASE_URL ?>/tenant/index.php" class="sidebar-item">📊 Dashboard</a>
            <a href="<?= BASE_URL ?>/tenant/pengajuan.php" class="sidebar-item sidebar-item--active">📝 Pengajuan</a>
            <a href="<?= BASE_URL ?>/tenant/kontrak.php" class="sidebar-item">📄 Kontrak</a>
            <a href="<?= BASE_URL ?>/tenant/maintenance.php" class="sidebar-item">🔧 Maintenance</a>
        </div>

        <div class="portal__content">
            <h1 style="color: #003A70; margin-bottom: 32px;">Pengajuan Sewa</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">Form Pengajuan Sewa</div>
                </div>
                <form method="POST" class="form" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">

                    <div class="form-group">
                        <label for="unit_id">Unit yang Diminati</label>
                        <select id="unit_id" name="unit_id" required>
                            <option value="">-- Pilih Unit --</option>
                            <?php foreach ($units as $unit): ?>
                            <option value="<?= $unit['id'] ?>">
                                <?= esc($unit['name']) ?> - Rp <?= number_format($unit['price_monthly'], 0, ',', '.') ?>/bulan
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group">
                            <label for="business_name">Nama Bisnis</label>
                            <input type="text" id="business_name" name="business_name" required>
                        </div>

                        <div class="form-group">
                            <label for="business_type">Tipe Bisnis</label>
                            <input type="text" id="business_type" name="business_type" placeholder="Kafe, Toko, dll">
                        </div>

                        <div class="form-group">
                            <label for="duration_months">Durasi (Bulan)</label>
                            <input type="number" id="duration_months" name="duration_months" min="1" value="12" required>
                        </div>

                        <div class="form-group">
                            <label for="doc">Dokumen Pendukung</label>
                            <input type="file" id="doc" name="doc" accept=".pdf,.jpg,.jpeg,.png" required>
                        </div>
                    </div>

                    <button type="submit" class="btn btn--primary">Kirim Pengajuan</button>
                </form>
            </div>

            <div class="card">
                <div class="card__header">
                    <div class="card__title">Riwayat Pengajuan</div>
                </div>

                <?php if (empty($apps)): ?>
                <div class="empty-state">
                    <div class="empty-state__message">Belum ada pengajuan sewa</div>
                </div>
                <?php else: ?>

                <div style="overflow-x: auto;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Unit</th>
                                <th>Bisnis</th>
                                <th>Durasi</th>
                                <th>Status</th>
                                <th>Catatan</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($apps as $app): ?>
                            <tr>
                                <td><?= esc($app['unit_name']) ?></td>
                                <td><?= esc($app['business_name']) ?></td>
                                <td><?= $app['duration_months'] ?> bulan</td>
                                <td><span class="badge badge--<?= esc($app['status']) ?>"><?= esc(ucfirst(str_replace('_', ' ', $app['status']))) ?></span></td>
                                <td><?= esc($app['admin_notes'] ?? '-') ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

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

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