<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/language_functions.php';

yetkili_mi('faturalar'); // Fatura görüntüleme yetkisi

// Initialize language
$current_language = getCurrentLanguage();
$translation_file = __DIR__ . "/../languages/{$current_language}.php";
$translations = file_exists($translation_file) ? require $translation_file : [];

// Translation function
if (!function_exists('__')) {
    function __($key, $params = []) {
        global $translations;
        $translation = $translations[$key] ?? $key;
        
        // Replace placeholders if any
        if (!empty($params)) {
            foreach ($params as $param => $value) {
                $translation = str_replace(':' . $param, $value, $translation);
            }
        }
        
        return $translation;
    }
}

$sayfa_baslik = __("sales_invoices");
$paraBirimi = getParaBirimiSembolu(); // Get currency symbol
$csrf_token = csrf_token_olustur(); // Generate CSRF token

// Filtreleme ve arama
$arama_sorgusu = temizle($_GET['arama'] ?? '');
$baslangic_tarihi = temizle($_GET['baslangic'] ?? '');
$bitis_tarihi = temizle($_GET['bitis'] ?? '');
$odeme_durumu_filtre = temizle($_GET['odeme_durumu'] ?? '');

$where_kosullari = ["b.tur = 'satis'", "b.sirket_id = ?"];
$parametreler = [$_SESSION['aktif_sirket_id']];

if (!empty($arama_sorgusu)) {
    $where_kosullari[] = "(c.ad_soyad LIKE ? OR b.aciklama LIKE ? OR b.id = ?)";
    $parametreler[] = "%$arama_sorgusu%";
    $parametreler[] = "%$arama_sorgusu%";
    $parametreler[] = $arama_sorgusu;
}
if (!empty($baslangic_tarihi)) {
    $where_kosullari[] = "b.tarih >= ?";
    $parametreler[] = $baslangic_tarihi;
}
if (!empty($bitis_tarihi)) {
    $where_kosullari[] = "b.tarih <= ?";
    $parametreler[] = $bitis_tarihi;
}
if ($odeme_durumu_filtre !== '') {
    if ($odeme_durumu_filtre == 'odendi') {
        // Tamamen ödenmiş faturalar
        $where_kosullari[] = "(b.tutar + b.toplam_kdv - b.indirim_tutari - b.odenen_tutar) <= 0.01";
    } elseif ($odeme_durumu_filtre == 'kismen') {
        // Kısmen ödenmiş faturalar (hem ödeme yapılmış hem de kalan borç var)
        $where_kosullari[] = "b.odenen_tutar > 0.01 AND (b.tutar + b.toplam_kdv - b.indirim_tutari - b.odenen_tutar) > 0.01";
    } elseif ($odeme_durumu_filtre == 'odenmedi') {
        // Hiç ödenmemiş faturalar
        $where_kosullari[] = "b.odenen_tutar <= 0.01";
    }
}

$where_sorgusu = !empty($where_kosullari) ? 'WHERE ' . implode(' AND ', $where_kosullari) : '';

// Sayfalama
$sayfa = filter_input(INPUT_GET, 'sayfa', FILTER_VALIDATE_INT) ?: 1;
$limit = 20;
$offset = ($sayfa - 1) * $limit;

try {
    // Toplam kayıt sayısı
    $stmt_sayac = $db->prepare("SELECT COUNT(b.id) FROM borclar b JOIN cariler c ON b.cari_id = c.id $where_sorgusu");
    $stmt_sayac->execute($parametreler);
    $toplam_kayit = $stmt_sayac->fetchColumn();
    $toplam_sayfa = ceil($toplam_kayit / $limit);

    // Faturaları getir
    $stmt = $db->prepare("
        SELECT 
            b.id, 
            b.tarih, 
            b.vade_tarihi, 
            c.ad_soyad as cari_adi, 
            (b.tutar + b.toplam_kdv - b.indirim_tutari) as toplam_tutar,
            (b.tutar + b.toplam_kdv - b.indirim_tutari - b.odenen_tutar) as kalan_tutar,
            COALESCE(
                CASE 
                    WHEN b.durum = 'odendi' THEN 'odendi'
                    WHEN b.durum = 'kismen_odendi' THEN 'kismen'
                    WHEN (b.tutar + b.toplam_kdv - b.indirim_tutari - b.odenen_tutar) <= 0.01 THEN 'odendi'
                    WHEN b.odenen_tutar > 0.01 AND (b.tutar + b.toplam_kdv - b.indirim_tutari - b.odenen_tutar) > 0.01 THEN 'kismen'
                    ELSE 'odenmedi'
                END,
                CASE 
                    WHEN (b.tutar + b.toplam_kdv - b.indirim_tutari - b.odenen_tutar) <= 0.01 THEN 'odendi'
                    WHEN b.odenen_tutar > 0.01 AND (b.tutar + b.toplam_kdv - b.indirim_tutari - b.odenen_tutar) > 0.01 THEN 'kismen'
                    ELSE 'odenmedi'
                END
            ) as odeme_durumu
        FROM borclar b
        JOIN cariler c ON b.cari_id = c.id
        $where_sorgusu
        ORDER BY b.id DESC
        LIMIT ? OFFSET ?
    ");
    
    $parametreler_limitli = array_merge($parametreler, [$limit, $offset]);

    foreach ($parametreler_limitli as $key => $val) {
        $stmt->bindValue($key + 1, $val, is_int($val) ? PDO::PARAM_INT : PDO::PARAM_STR);
    }
    $stmt->execute();
    $faturalar = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $_SESSION['hata'] = "Veritabanı hatası: " . $e->getMessage();
    $faturalar = [];
    $toplam_kayit = 0;
    $toplam_sayfa = 0;
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= temizle($sayfa_baslik) ?> - Odjoo Yönetim</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2><i class="bi bi-receipt"></i> <?= temizle($sayfa_baslik) ?></h2>
            <a href="satis_yeni.php" class="btn btn-success"><i class="bi bi-plus-circle"></i> <?= __("new_sales_invoice") ?></a>
        </div>

        <?php if (isset($_SESSION['mesaj'])): ?>
            <div class="alert alert-success"><?= $_SESSION['mesaj'] ?></div>
            <?php unset($_SESSION['mesaj']); ?>
        <?php endif; ?>
        <?php if (isset($_SESSION['hata'])): ?>
            <div class="alert alert-danger"><?= $_SESSION['hata'] ?></div>
            <?php unset($_SESSION['hata']); ?>
        <?php endif; ?>

        <!-- Filtreleme Formu -->
        <div class="card mb-4">
            <div class="card-header bg-light">
                <i class="bi bi-funnel"></i> <?= __("filter") ?>
            </div>
            <div class="card-body">
                <form method="get" class="row g-3">
                    <div class="col-md-3">
                        <label for="arama" class="form-label"><?= __("search") ?> (<?= __("customer") ?>/Not/No):</label>
                        <input type="text" class="form-control" id="arama" name="arama" value="<?= htmlspecialchars($arama_sorgusu) ?>">
                    </div>
                    <div class="col-md-2">
                        <label for="baslangic" class="form-label"><?= __("from_date") ?>:</label>
                        <input type="date" class="form-control" id="baslangic" name="baslangic" value="<?= htmlspecialchars($baslangic_tarihi) ?>">
                    </div>
                    <div class="col-md-2">
                        <label for="bitis" class="form-label"><?= __("to_date") ?>:</label>
                        <input type="date" class="form-control" id="bitis" name="bitis" value="<?= htmlspecialchars($bitis_tarihi) ?>">
                    </div>
                    <div class="col-md-3">
                        <label for="odeme_durumu" class="form-label"><?= __("payment_status") ?>:</label>
                        <select class="form-select" id="odeme_durumu" name="odeme_durumu">
                            <option value=""><?= __("all") ?></option>
                            <option value="odendi" <?= $odeme_durumu_filtre === 'odendi' ? 'selected' : '' ?>><?= __("paid") ?></option>
                            <option value="kismen" <?= $odeme_durumu_filtre === 'kismen' ? 'selected' : '' ?>><?= __("partially_paid") ?></option>
                            <option value="odenmedi" <?= $odeme_durumu_filtre === 'odenmedi' ? 'selected' : '' ?>><?= __("unpaid") ?></option>
                        </select>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2"><i class="bi bi-funnel"></i> <?= __("filter") ?></button>
                        <a href="satis_faturalari.php" class="btn btn-secondary"><i class="bi bi-arrow-counterclockwise"></i></a>
                    </div>
                </form>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-striped table-hover table-bordered">
                <thead class="table-light">
                    <tr>
                        <th><?= __("invoice_number") ?></th>
                        <th><?= __("customer") ?></th>
                        <th><?= __("date") ?></th>
                        <th><?= __("due_date") ?></th>
                        <th><?= __("amount") ?></th>
                        <th><?= __("payment_status") ?></th>
                        <th><?= __("actions") ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($faturalar)): ?>
                        <tr>
                            <td colspan="7" class="text-center"><?= __("no_records_found") ?></td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($faturalar as $fatura): ?>
                            <tr>
                                <td>#<?= str_pad($fatura['id'], 6, '0', STR_PAD_LEFT) ?></td>
                                <td><?= temizle($fatura['cari_adi']) ?></td>
                                <td><?= date('d.m.Y', strtotime($fatura['tarih'])) ?></td>
                                <td><?= $fatura['vade_tarihi'] ? date('d.m.Y', strtotime($fatura['vade_tarihi'])) : '-' ?></td>
                                <td><?= number_format($fatura['toplam_tutar'], 2, ',', '.') ?> <?= $paraBirimi ?></td>
                                <td>
                                    <?php 
                                    $toplam_borc = $fatura['toplam_tutar'];
                                    $kalan_borc = $fatura['kalan_tutar'];
                                    $odenen_miktar = $toplam_borc - $kalan_borc;
                                    
                                    switch ($fatura['odeme_durumu']) {
                                        case 'odendi':
                                            echo '<span class="badge bg-success">' . strtoupper(__('paid')) . '</span>';
                                            break;
                                        case 'kismen':
                                            $yuzde_odenen = round(($odenen_miktar / $toplam_borc) * 100);
                                            echo '<span class="badge bg-warning text-dark">' . strtoupper(__('partially_paid')) . ' (' . $yuzde_odenen . '%)</span>';
                                            break;
                                        default:
                                            echo '<span class="badge bg-danger">' . strtoupper(__('unpaid')) . '</span>';
                                    }
                                    ?>
                                </td>
                                <td>
                                    <a href="fatura_goruntule.php?id=<?= $fatura['id'] ?>&tur=satis" class="btn btn-info btn-sm" title="<?= __('view') ?>"><i class="bi bi-eye"></i></a>
                                    <a href="borc_duzenle.php?id=<?= $fatura['id'] ?>" class="btn btn-warning btn-sm" title="<?= __('edit') ?>"><i class="bi bi-pencil"></i></a>
                                    <?php if (yetkili_mi(['admin', 'satis_islemleri', 'alis_islemleri'], false)): ?>
                                    <form action="fatura_sil.php" method="POST" onsubmit="return confirm('<?= addslashes(__('confirm_invoice_delete')) ?>');" class="d-inline">
                                        <input type="hidden" name="borc_id" value="<?= $fatura['id'] ?>">
                                        <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                                        <button type="submit" class="btn btn-danger btn-sm" title="<?= __('delete') ?>">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($toplam_sayfa > 1): ?>
        <nav aria-label="<?= __('pagination_navigation') ?>">
            <ul class="pagination justify-content-center">
                <?php 
                $query_params = http_build_query([
                    'arama' => $arama_sorgusu,
                    'baslangic' => $baslangic_tarihi,
                    'bitis' => $bitis_tarihi,
                    'odeme_durumu' => $odeme_durumu_filtre
                ]);
                
                // Previous page link
                if ($sayfa > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?sayfa=<?= $sayfa - 1 ?>&<?= $query_params ?>" aria-label="<?= __('previous') ?>">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
                
                <?php for ($i = 1; $i <= $toplam_sayfa; $i++): ?>
                    <li class="page-item <?= $i == $sayfa ? 'active' : '' ?>">
                        <a class="page-link" href="?sayfa=<?= $i ?>&<?= $query_params ?>"><?= $i ?></a>
                    </li>
                <?php endfor; ?>
                
                <?php // Next page link
                if ($sayfa < $toplam_sayfa): ?>
                    <li class="page-item">
                        <a class="page-link" href="?sayfa=<?= $sayfa + 1 ?>&<?= $query_params ?>" aria-label="<?= __('next') ?>">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>
            <div class="text-center text-muted">
                <?= str_replace([':current', ':total'], [$sayfa, $toplam_sayfa], __('pagination_info')) ?>
            </div>
        </nav>
        <?php endif; ?>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <?php include __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>
