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

$sayfa_baslik = "Arama";

// Arama parametreleri
$arama_terimi = isset($_GET['q']) ? trim($_GET['q']) : '';
$kategori = isset($_GET['kategori']) ? $_GET['kategori'] : 'hepsi';

// Arama sonuçları
$cariler = [];
$borclar = [];
$hesap_hareketleri = [];

if (!empty($arama_terimi)) {
    try {
        // Cari arama
        $cari_sql = "SELECT id, ad_soyad, telefon, eposta, bakiye FROM cariler 
                     WHERE (ad_soyad LIKE :arama OR telefon LIKE :arama OR eposta LIKE :arama) AND sirket_id = :sirket_id
                     ORDER BY ad_soyad ASC LIMIT 20";
        $stmt_cari = $db->prepare($cari_sql);
        $arama_param = "%{$arama_terimi}%";
        $stmt_cari->bindParam(':arama', $arama_param);
        $stmt_cari->bindValue(':sirket_id', $_SESSION['aktif_sirket_id'] ?? 0, PDO::PARAM_INT);
        $stmt_cari->execute();
        $cariler = $stmt_cari->fetchAll(PDO::FETCH_ASSOC);
        
        // Borç/Alacak arama
        $borc_sql = "SELECT b.id, b.tur, b.tutar, b.tarih, b.vade_tarihi, b.aciklama, c.ad_soyad as cari_adi 
                     FROM borclar b 
                     JOIN cariler c ON b.cari_id = c.id AND c.sirket_id = b.sirket_id
                     WHERE (c.ad_soyad LIKE :arama OR b.aciklama LIKE :arama) AND b.sirket_id = :sirket_id
                     ORDER BY b.tarih DESC LIMIT 20";
        $stmt_borc = $db->prepare($borc_sql);
        $stmt_borc->bindParam(':arama', $arama_param);
        $stmt_borc->bindValue(':sirket_id', $_SESSION['aktif_sirket_id'] ?? 0, PDO::PARAM_INT);
        $stmt_borc->execute();
        $borclar = $stmt_borc->fetchAll(PDO::FETCH_ASSOC);
        
        // Hesap hareketleri arama
        $hareket_sql = "SELECT hh.id, hh.tur, hh.tutar, hh.tarih, hh.aciklama, c.ad_soyad as cari_adi, h.hesap_adi 
                        FROM hesap_hareketleri hh 
                        LEFT JOIN cariler c ON hh.cari_id = c.id AND c.sirket_id = hh.sirket_id
                        LEFT JOIN hesaplar h ON hh.hesap_id = h.id AND h.sirket_id = hh.sirket_id
                        WHERE (c.ad_soyad LIKE :arama OR hh.aciklama LIKE :arama OR h.hesap_adi LIKE :arama) AND hh.sirket_id = :sirket_id
                        ORDER BY hh.tarih DESC LIMIT 20";
        $stmt_hareket = $db->prepare($hareket_sql);
        $stmt_hareket->bindParam(':arama', $arama_param);
        $stmt_hareket->bindValue(':sirket_id', $_SESSION['aktif_sirket_id'] ?? 0, PDO::PARAM_INT);
        $stmt_hareket->execute();
        $hesap_hareketleri = $stmt_hareket->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        error_log("Arama hatası: " . $e->getMessage());
        $_SESSION['hata'] = "Arama yapılırken bir hata oluştu.";
    }
}
?>
<!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 - <?= temizle($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">
    <style>
        .search-result-item {
            transition: transform 0.2s ease-in-out;
            border-left: 4px solid transparent;
        }
        .search-result-item:hover {
            transform: translateX(5px);
            border-left-color: #0d6efd;
        }
        .badge-cari { background-color: #6610f2; }
        .badge-borc { background-color: #dc3545; }
        .badge-alacak { background-color: #198754; }
        .badge-hareket { background-color: #0dcaf0; color: #000; }
        
        /* Mobil uyumluluk */
        @media (max-width: 768px) {
            .card-title { font-size: 1.1rem; }
            .search-result-item { padding: 10px; }
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container mt-4">
        <h2><i class="bi bi-search"></i> <?= temizle($sayfa_baslik) ?></h2>
        <hr>
        
        <!-- Arama Formu -->
        <div class="card shadow-sm mb-4">
            <div class="card-body">
                <form method="get" class="row g-3">
                    <div class="col-md-8">
                        <div class="input-group">
                            <span class="input-group-text"><i class="bi bi-search"></i></span>
                            <input type="text" class="form-control" name="q" placeholder="Cari, açıklama veya hesap adı ara..." value="<?= htmlspecialchars($arama_terimi) ?>">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="kategori">
                            <option value="hepsi" <?= $kategori == 'hepsi' ? 'selected' : '' ?>>Tümü</option>
                            <option value="cariler" <?= $kategori == 'cariler' ? 'selected' : '' ?>>Cariler</option>
                            <option value="borclar" <?= $kategori == 'borclar' ? 'selected' : '' ?>>Borçlar/Alacaklar</option>
                            <option value="hareketler" <?= $kategori == 'hareketler' ? 'selected' : '' ?>>Hesap Hareketleri</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">Ara</button>
                    </div>
                </form>
            </div>
        </div>
        
        <?php if (empty($arama_terimi)): ?>
            <div class="alert alert-info">
                <i class="bi bi-info-circle-fill me-2"></i> Arama yapmak için yukarıdaki formu kullanın.
            </div>
        <?php elseif (empty($cariler) && empty($borclar) && empty($hesap_hareketleri)): ?>
            <div class="alert alert-warning">
                <i class="bi bi-exclamation-triangle-fill me-2"></i> "<?= htmlspecialchars($arama_terimi) ?>" için sonuç bulunamadı.
            </div>
        <?php else: ?>
            <!-- Arama Sonuçları -->
            
            <?php if (!empty($cariler) && ($kategori == 'hepsi' || $kategori == 'cariler')): ?>
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-light">
                    <h5 class="card-title mb-0"><i class="bi bi-people me-2"></i>Cariler</h5>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush">
                        <?php foreach ($cariler as $cari): ?>
                        <a href="cari_detay.php?id=<?= $cari['id'] ?>" class="list-group-item list-group-item-action search-result-item">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1"><?= temizle($cari['ad_soyad']) ?> <span class="badge badge-cari">Cari</span></h6>
                                    <small class="text-muted">
                                        <?php if (!empty($cari['telefon'])): ?>
                                        <i class="bi bi-telephone me-1"></i> <?= temizle($cari['telefon']) ?>
                                        <?php endif; ?>
                                        <?php if (!empty($cari['eposta'])): ?>
                                        <i class="bi bi-envelope ms-2 me-1"></i> <?= temizle($cari['eposta']) ?>
                                        <?php endif; ?>
                                    </small>
                                </div>
                                <span class="badge <?= $cari['bakiye'] >= 0 ? 'bg-success' : 'bg-danger' ?>">
                                    <?= number_format($cari['bakiye'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?>
                                </span>
                            </div>
                        </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if (!empty($borclar) && ($kategori == 'hepsi' || $kategori == 'borclar')): ?>
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-light">
                    <h5 class="card-title mb-0"><i class="bi bi-cash-stack me-2"></i>Borçlar/Alacaklar</h5>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush">
                        <?php foreach ($borclar as $borc): ?>
                        <div class="list-group-item search-result-item">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">
                                        <?= temizle($borc['cari_adi']) ?> 
                                        <span class="badge <?= $borc['tur'] == 'satis' ? 'badge-alacak' : 'badge-borc' ?>">
                                            <?= $borc['tur'] == 'satis' ? 'Alacak' : 'Borç' ?>
                                        </span>
                                    </h6>
                                    <p class="mb-1 small"><?= temizle($borc['aciklama']) ?></p>
                                    <small class="text-muted">
                                        <i class="bi bi-calendar me-1"></i> <?= date('d.m.Y', strtotime($borc['tarih'])) ?>
                                        <?php if (!empty($borc['vade_tarihi'])): ?>
                                        <i class="bi bi-calendar-check ms-2 me-1"></i> Vade: <?= date('d.m.Y', strtotime($borc['vade_tarihi'])) ?>
                                        <?php endif; ?>
                                    </small>
                                </div>
                                <span class="badge <?= $borc['tur'] == 'satis' ? 'bg-success' : 'bg-danger' ?>">
                                    <?= number_format($borc['tutar'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?>
                                </span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if (!empty($hesap_hareketleri) && ($kategori == 'hepsi' || $kategori == 'hareketler')): ?>
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-light">
                    <h5 class="card-title mb-0"><i class="bi bi-arrow-left-right me-2"></i>Hesap Hareketleri</h5>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush">
                        <?php foreach ($hesap_hareketleri as $hareket): ?>
                        <div class="list-group-item search-result-item">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">
                                        <?= temizle($hareket['hesap_adi']) ?> 
                                        <span class="badge badge-hareket">Hareket</span>
                                        <span class="badge <?= $hareket['tur'] == 'giris' ? 'bg-success' : 'bg-danger' ?>">
                                            <?= $hareket['tur'] == 'giris' ? 'Giriş' : 'Çıkış' ?>
                                        </span>
                                    </h6>
                                    <p class="mb-1 small"><?= temizle($hareket['aciklama']) ?></p>
                                    <small class="text-muted">
                                        <i class="bi bi-calendar me-1"></i> <?= date('d.m.Y H:i', strtotime($hareket['tarih'])) ?>
                                        <?php if (!empty($hareket['cari_adi'])): ?>
                                        <i class="bi bi-person ms-2 me-1"></i> <?= temizle($hareket['cari_adi']) ?>
                                        <?php endif; ?>
                                    </small>
                                </div>
                                <span class="badge <?= $hareket['tur'] == 'giris' ? 'bg-success' : 'bg-danger' ?>">
                                    <?= number_format($hareket['tutar'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?>
                                </span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            
        <?php endif; ?>
    </div>
    <?php include __DIR__ . '/../includes/footer.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
