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

$apartmanlar = db::execAll("SELECT ID, apartman_adi FROM tb_apartman ORDER BY apartman_adi");
$gider = db::getId("tb_gider", $_GET['id']);

if ($_POST) {
    db::update("tb_gider", $_GET['id'], [
        'apartmanID' => $_POST['apartmanID'],
        'tutar'      => $_POST['tutar'],
        'tarih'      => $_POST['tarih'],
        'kategori'   => $_POST['kategori'] ?? null
    ]);

    header("Location: index.php");
    exit;
}

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

<div class="flex-fill p-4">
    <h4>Gider Düzenle</h4>

    <form method="post" style="max-width:500px; border:1px solid #ccc; padding:20px; border-radius:5px;">

        <div class="mb-2">
            <label class="form-label">Apartman</label>
            <select name="apartmanID" class="form-select" required>
                <?php foreach ($apartmanlar as $a): ?>
                    <option value="<?= $a->ID ?>" <?= $gider->apartmanID == $a->ID ? 'selected' : '' ?>>
                        <?= $a->apartman_adi ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="mb-2">
            <label class="form-label">Tutar</label>
            <input type="number" step="0.01" name="tutar" class="form-control" value="<?= $gider->tutar ?>" required>
        </div>

        <div class="mb-2">
            <label class="form-label">Tarih</label>
            <input type="date" name="tarih" class="form-control" value="<?= $gider->tarih ?>" required>
        </div>

        <div class="mb-2">
            <label class="form-label">Kategori (Opsiyonel)</label>
            <select name="kategori" class="form-select">
                <option value="">Seçiniz</option>
                <option value="Elektrik" <?= $gider->kategori == 'Elektrik' ? 'selected' : '' ?>>Elektrik</option>
                <option value="Su" <?= $gider->kategori == 'Su' ? 'selected' : '' ?>>Su</option>
                <option value="Asansör Bakımı" <?= $gider->kategori == 'Asansör Bakımı' ? 'selected' : '' ?>>Asansör Bakımı</option>
                <option value="Diğer" <?= $gider->kategori == 'Diğer' ? 'selected' : '' ?>>Diğer</option>
            </select>
        </div>

        <button class="btn btn-primary">Güncelle</button>
        <a href="index.php" class="btn btn-secondary">İptal</a>
    </form>
</div>

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