<?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");

if ($_POST) {
    db::insert("tb_gider", [
        'apartmanID' => $_POST['apartmanID'],
        'tutar'      => $_POST['tutar'],
        'tarih'      => $_POST['tarih'],
        'kategori'   => $_POST['kategori'] ?? null
    ]);
    // 2️⃣ Kasadan düş
    db::insert("tb_kasa", [
        'tarih'   => $_POST['tarih'],
        'aciklama' => "Gider: " . ($_POST['kategori'] ?? 'Diğer'),
        'tutar'   => $_POST['tutar'],
        'kategori'   => $_POST['kategori'] ?? null,
        'tip' => 'ÇIKIŞ'
    ]);
    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 Ekle</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 ?>"><?= $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" required>
        </div>

        <div class="mb-2">
            <label class="form-label">Tarih</label>
            <input type="date" name="tarih" class="form-control" 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">Elektrik</option>
                <option value="Su">Su</option>
                <option value="Asansör Bakımı">Asansör Bakımı</option>
                <option value="Diğer">Diğer</option>
            </select>
        </div>

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

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