<?php
require_once __DIR__ . '/../includes/config.php';
yetkili_mi();

$sayfa_baslik = "Borç Ödemeleri";

// ÖDEME EKLEME
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['odeme_ekle'])) {
    if(!csrf_token_dogrula($_POST['csrf_token'])) die("Geçersiz token!");
    
    $borc_id = (int)$_POST['borc_id'];
    $hesap_id = (int)$_POST['hesap_id'];
    $tutar = (float)$_POST['tutar'];
    $tarih = $_POST['tarih'];
    $aciklama = temizle($_POST['aciklama']);
    
    try {
        $db->beginTransaction();
        
        // 1. Borç bilgilerini kontrol et
        $borc = $db->query("SELECT * FROM borclar WHERE id = $borc_id")->fetch();
        if(!$borc) throw new Exception("Borç bulunamadı!");
        
        // 2. Ödemeyi kaydet
        $stmt = $db->prepare("INSERT INTO borc_odemeleri (borc_id, tutar, aciklama, tarih) VALUES (?,?,?,?)");
        $stmt->execute([$borc_id, $tutar, $aciklama, $tarih]);
        
        // 3. Hesap hareketi oluştur
        $db->prepare("INSERT INTO hesap_hareketleri (hesap_id, cari_id, tur, tutar, aciklama, baglanti_id) 
                     VALUES (?, ?, 'odeme', ?, ?, ?)")
           ->execute([$hesap_id, $borc['cari_id'], -$tutar, $aciklama, $borc_id]);
        
        // 4. Hesap bakiyesini düşür
        $db->prepare("UPDATE hesaplar SET bakiye = bakiye - ? WHERE id = ?")
           ->execute([$tutar, $hesap_id]);
        
        // 5. Cari borcunu güncelle
        $db->prepare("UPDATE cariler SET toplam_borc = toplam_borc - ? WHERE id = ?")
           ->execute([$tutar, $borc['cari_id']]);
        
        $db->commit();
        $_SESSION['mesaj'] = "Ödeme başarıyla kaydedildi!";
    } catch(Exception $e) {
        $db->rollBack();
        $_SESSION['hata'] = "Hata: ".$e->getMessage();
    }
    header("Location: borc_odemeleri.php"); exit();
}

// BORÇ LİSTESİ
try {
    $borclar = $db->query("
        SELECT b.*, c.ad_soyad, k.kategori_adi,
               (b.tutar - COALESCE(SUM(o.tutar), 0)) as kalan_borc
        FROM borclar b
        LEFT JOIN borc_odemeleri o ON b.id = o.borc_id
        JOIN cariler c ON b.cari_id = c.id
        JOIN kategoriler k ON b.kategori_id = k.id
        GROUP BY b.id
        HAVING kalan_borc > 0
        ORDER BY b.vade_tarihi ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $hesaplar = $db->query("SELECT * FROM hesaplar")->fetchAll();
} catch(PDOException $e) {
    die("Hata: ".$e->getMessage());
}

$csrf_token = csrf_token_olustur();
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Odjoo Yönetim - <?= $sayfa_baslik ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
</head
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container-xl mt-4">
        <div class="row">
            <div class="col-md-5">
                <div class="card shadow">
                    <div class="card-header bg-danger text-white">
                        <h5 class="mb-0"><i class="bi bi-cash"></i> Ödeme Yap</h5>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                            
                            <div class="mb-3">
                                <label>Borç Seçin</label>
                                <select name="borc_id" class="form-select" required>
                                    <?php foreach($borclar as $borc): ?>
                                    <option value="<?= $borc['id'] ?>">
                                        <?= temizle($borc['ad_soyad']) ?> - 
                                        <?= number_format($borc['kalan_borc'], 2) . ' ' . getParaBirimiSembolu() ?>
                                        (Vade: <?= $borc['vade_tarihi'] ? date('d.m.Y', strtotime($borc['vade_tarihi'])) : 'Belirsiz' ?>)
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label>Tutar</label>
                                    <input type="number" step="0.01" name="tutar" class="form-control" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Hesap</label>
                                    <select name="hesap_id" class="form-select" required>
                                        <?php foreach($hesaplar as $hesap): ?>
                                        <option value="<?= $hesap['id'] ?>"><?= temizle($hesap['hesap_adi']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label>Tarih</label>
                                <input type="date" name="tarih" class="form-control" value="<?= date('Y-m-d') ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label>Açıklama</label>
                                <textarea name="aciklama" class="form-control" rows="2"></textarea>
                            </div>
                            
                            <button type="submit" name="odeme_ekle" class="btn btn-danger w-100">
                                <i class="bi bi-check2-circle"></i> Ödeme Yap
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-md-7">
                <div class="card shadow">
                    <div class="card-header bg-secondary text-white">
                        <h5 class="mb-0"><i class="bi bi-list"></i> Ödenmemiş Borçlar</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Cari</th>
                                        <th>Kategori</th>
                                        <th class="text-end">Kalan Borç</th>
                                        <th>Vade Tarihi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($borclar as $borc): ?>
                                    <tr class="<?= $borc['vade_tarihi'] && strtotime($borc['vade_tarihi']) < time() ? 'table-danger' : '' ?>">
                                        <td><?= temizle($borc['ad_soyad']) ?></td>
                                        <td><?= temizle($borc['kategori_adi']) ?></td>
                                        <td class="text-end"><?= number_format($borc['kalan_borc'], 2) . ' ' . getParaBirimiSembolu() ?></td>
                                        <td><?= $borc['vade_tarihi'] ? date('d.m.Y', strtotime($borc['vade_tarihi'])) : '-' ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
	<?php include __DIR__ . "/../includes/footer.php"; ?>
</body>
</html>
