<?php
require_once '../../config.php';
require_once ROOT . 'app/db.php';

$apartman = db::getId("tb_apartman", $_GET['id']);
$hata = '';

if ($_POST) {
    if ((int)$_POST['daire_sayisi'] < $apartman->kayitli_daire) {
        $hata = "Toplam daire sayısı mevcut kayıtlı dairelerden az olamaz!";
    } else {
        db::update("tb_apartman", $_GET['id'], [
            'apartman_adi' => $_POST['apartman_adi'],
            'adres'        => $_POST['adres'],
            'yonetici_adi' => $_POST['yonetici_adi'],
            'daire_sayisi' => $_POST['daire_sayisi']
        ]);
        header("Location: index.php");
        exit;
    }
}

require_once ROOT . 'layout/header.php';
require_once ROOT . 'layout/sidebar.php';
?>

<div class="flex-fill p-4">

    <h3 class="mb-4">🏢 Apartman Düzenle</h3>

    <div class="card shadow-sm border p-3" style="max-width:700px;">

        <?php if ($hata): ?>
            <div class="alert alert-danger"><?= $hata ?></div>
        <?php endif; ?>

        <form method="post">

            <div class="row g-3 mb-3">
                <div class="col-md-6">
                    <label class="form-label fw-bold">Apartman Adı</label>
                    <input type="text" name="apartman_adi" class="form-control" value="<?= $apartman->apartman_adi ?>" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold">Yönetici Adı</label>
                    <input type="text" name="yonetici_adi" class="form-control" value="<?= $apartman->yonetici_adi ?>">
                </div>
            </div>

            <div class="row g-3 mb-3">
                <div class="col-md-6">
                    <label class="form-label fw-bold">Toplam Daire Sayısı</label>
                    <input type="number" name="daire_sayisi" class="form-control" value="<?= $apartman->daire_sayisi ?>" required>
                    <small class="text-muted">Mevcut kayıtlı daire: <?= $apartman->kayitli_daire ?></small>
                </div>
            </div>

            <div class="mb-3">
                <label class="form-label fw-bold">Adres</label>
                <textarea name="adres" class="form-control" rows="3"><?= $apartman->adres ?></textarea>
            </div>

            <div class="d-flex gap-2 mt-3">
                <a href="index.php" class="btn btn-secondary">İptal</a>
                <button class="btn btn-primary">Güncelle</button>
            </div>

        </form>
    </div>
</div>

<?php require_once ROOT . 'layout/footer.php'; ?>