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

require_login('tenant');
$page_title = 'Maintenance Request - 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);
    $description = trim($_POST['description'] ?? '');

    if ($unit_id && $description) {
        $photo_path = handle_upload('photo', 'service-report');

        $stmt = $conn->prepare('INSERT INTO maintenance_requests (user_id, unit_id, description, photo_path) VALUES (?, ?, ?, ?)');
        $stmt->bind_param('iiss', $user_id, $unit_id, $description, $photo_path);

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

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

// Get user's units
$units = [];
$result = $conn->query("
    SELECT DISTINCT ru.* FROM rental_units ru
    JOIN rental_applications ra ON ra.unit_id = ru.id
    WHERE ra.user_id = $user_id AND ra.status = 'approved'
");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $units[] = $row;
    }
}

// Get maintenance requests
$requests = [];
$result = $conn->query("SELECT mr.*, ru.name as unit_name FROM maintenance_requests mr JOIN rental_units ru ON mr.unit_id = ru.id WHERE mr.user_id = $user_id ORDER BY mr.created_at DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $requests[] = $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">📝 Pengajuan</a>
            <a href="<?= BASE_URL ?>/tenant/kontrak.php" class="sidebar-item">📄 Kontrak</a>
            <a href="<?= BASE_URL ?>/tenant/maintenance.php" class="sidebar-item sidebar-item--active">🔧 Maintenance</a>
        </div>

        <div class="portal__content">
            <h1 style="color: #003A70; margin-bottom: 32px;">Maintenance Request</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">Laporan Maintenance</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</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']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="description">Deskripsi Masalah</label>
                        <textarea id="description" name="description" required></textarea>
                    </div>

                    <div class="form-group">
                        <label for="photo">Foto</label>
                        <input type="file" id="photo" name="photo" accept="image/*">
                    </div>

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

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

                <?php if (empty($requests)): ?>
                <div class="empty-state">
                    <div class="empty-state__message">Belum ada maintenance request</div>
                </div>
                <?php else: ?>

                <div style="overflow-x: auto;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Unit</th>
                                <th>Deskripsi</th>
                                <th>Status</th>
                                <th>Tanggal</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($requests as $req): ?>
                            <tr>
                                <td><?= esc($req['unit_name']) ?></td>
                                <td><?= esc(substr($req['description'], 0, 50)) ?>...</td>
                                <td><span class="badge badge--<?= esc($req['status']) ?>"><?= esc(ucfirst($req['status'])) ?></span></td>
                                <td><?= format_datetime($req['created_at']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

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

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