<?php
require_once __DIR__ . '/../includes/config.php';
yetkili_mi('faturalar'); // Check invoice view permission

$fatura_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$fatura_turu = temizle($_GET['tur'] ?? 'satis');

if (!$fatura_id) {
    $_SESSION['hata'] = __("error_invalid_invoice_id");
    $redirect_url = ($fatura_turu == 'satis') ? 'satis_faturalari.php' : 'alis_faturalari.php';
    header("Location: $redirect_url");
    exit();
}

// Get the invoice's currency from the borclar table
$paraBirimi = $fatura['para_birimi'] ?? 'TL'; // Default to TL if not set
$csrf_token = csrf_token_olustur();

$tablo_adi = 'borclar';
$sayfa_baslik = ($fatura_turu == 'satis') ? __("sales_invoice") : __("purchase_invoice");
$cari_etiket = ($fatura_turu == 'satis') ? __("customer") : __("supplier");
$geri_don_url = ($fatura_turu == 'satis') ? 'satis_faturalari.php' : 'alis_faturalari.php';

try {
    // Fatura (borç) bilgilerini çek
    $stmt_borc = $db->prepare("SELECT * FROM borclar WHERE id = ? AND sirket_id = ?");
    $stmt_borc->execute([$fatura_id, $_SESSION['aktif_sirket_id']]);
    $fatura = $stmt_borc->fetch(PDO::FETCH_ASSOC);

    if (!$fatura) {
        throw new Exception(__("error_invoice_not_found"));
    }
    
    // Firma (şirket) bilgilerini çek
    $stmt_firma = $db->prepare("SELECT * FROM sirketler WHERE id = ?");
    $stmt_firma->execute([$_SESSION['aktif_sirket_id']]);
    $firma = $stmt_firma->fetch(PDO::FETCH_ASSOC);

    // Cari (müşteri/tedarikçi) bilgilerini çek
    $stmt_cari = $db->prepare("SELECT * FROM cariler WHERE id = ? AND sirket_id = ?");
    $stmt_cari->execute([$fatura['cari_id'], $_SESSION['aktif_sirket_id']]);
    $cari = $stmt_cari->fetch(PDO::FETCH_ASSOC);
    
    // Set the invoice currency, default to TL if not set
    $paraBirimi = !empty($fatura['para_birimi']) ? $fatura['para_birimi'] : 'TL';

    // Fatura detaylarını (ürünleri) çek
    $stmt_detaylar = $db->prepare("
        SELECT fd.*, u.urun_adi, u.birim, 
               CASE 
                   WHEN b.tur = 'satis' THEN u.satis_para_birimi 
                   ELSE u.alis_para_birimi 
               END as urun_para_birimi
        FROM fatura_detaylari fd
        JOIN urunler u ON fd.urun_id = u.id
        JOIN borclar b ON fd.borc_id = b.id
        WHERE fd.borc_id = ?
    ");
    $stmt_detaylar->execute([$fatura_id]);
    $detaylar = $stmt_detaylar->fetchAll(PDO::FETCH_ASSOC);

    // Toplamları ve kalan tutarı hesapla
    $ara_toplam = $fatura['tutar'];
    $toplam_kdv = $fatura['toplam_kdv'];
    $indirim = $fatura['indirim_tutari'];
    $odenen_tutar = $fatura['odenen_tutar'];
    $genel_toplam = $ara_toplam + $toplam_kdv - $indirim;
    $kalan_tutar = $genel_toplam - $odenen_tutar;

    // Ödeme durumunu güncelleme isteği (POST)
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['islem']) && $_POST['islem'] === 'odeme_durumu_guncelle') {
        if (!csrf_token_dogrula($_POST['csrf_token'] ?? '')) {
            throw new Exception(__('error_invalid_token'));
        }

        $yeni_durum = $_POST['yeni_durum'] ?? 'odenmedi';

        // Normalize ve doğrula
        if (!in_array($yeni_durum, ['odenmedi','kismen_odendi','odendi'], true)) {
            throw new Exception(__('error_invalid_status'));
        }

        $guncel_odenen = 0.0;
        if ($yeni_durum === 'odendi') {
            $guncel_odenen = (float)$genel_toplam; // tamamı ödenmiş kabul
        } elseif ($yeni_durum === 'kismen_odendi') {
            // Kısmi tutar manuel girilmiyor; mevcut odenen_tutar değeri korunur
            $guncel_odenen = (float)$odenen_tutar;
        } else { // odenmedi
            $guncel_odenen = 0.0;
        }

        // Veritabanını güncelle (sadece borclar tablosu; hareket oluşturmaz)
        $stmt_upd = $db->prepare("UPDATE borclar SET odenen_tutar = :odenen, durum = :durum, odeme_durumu = :durum_str WHERE id = :id AND sirket_id = :sirket_id");
        $durum_str = $yeni_durum; // uyumlu string alan
        $stmt_upd->execute([
            ':odenen' => $guncel_odenen,
            ':durum' => $yeni_durum,
            ':durum_str' => $durum_str,
            ':id' => $fatura_id,
            ':sirket_id' => $_SESSION['aktif_sirket_id'],
        ]);

        $_SESSION['mesaj'] = __('success_payment_status_updated');
        // Değerleri belgeden de güncelle
        $fatura['odenen_tutar'] = $guncel_odenen;
        $fatura['durum'] = $yeni_durum;
        $fatura['odeme_durumu'] = $durum_str;
        $odenen_tutar = $guncel_odenen;
        $kalan_tutar = $genel_toplam - $odenen_tutar;
    }

} catch (PDOException $e) {
    error_log("Invoice view error: " . $e->getMessage());
    $_SESSION['hata'] = __("error_database") . ": " . $e->getMessage();
    header("Location: $geri_don_url");
    exit();
}
?>
<!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) ?> - <?= __("app_name") ?></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">
    <style>
        @media print {
            .no-print { display: none !important; }
            .print-only { display: block !important; }
        }
        .fatura-header { border-bottom: 2px solid #dee2e6; padding-bottom: 1rem; margin-bottom: 2rem; }
        .fatura-footer { border-top: 2px solid #dee2e6; padding-top: 1rem; margin-top: 2rem; }
        .totals-table td, .totals-table th { border: none; }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container mt-4">
        <div class="card shadow-sm">
            <div class="card-header bg-light d-flex justify-content-between align-items-center no-print">
                <h4 class="mb-0"><i class="bi bi-receipt-cutoff"></i> <?= temizle($sayfa_baslik) ?></h4>
                <div>
                    <?php if ($fatura_turu == 'satis' && $fatura['durum'] != 'odendi'): ?>
                        <a href="odeme_al.php?borc_id=<?= $fatura_id ?>&cari_id=<?= $fatura['cari_id'] ?>" class="btn btn-success btn-sm">
                            <i class="bi bi-cash-coin"></i> Tahsilat Ekle
                        </a>
                    <?php elseif ($fatura_turu == 'alis' && $fatura['durum'] != 'odendi'): ?>
                        <a href="odeme_yap.php?borc_id=<?= $fatura_id ?>&cari_id=<?= $fatura['cari_id'] ?>" class="btn btn-danger btn-sm">
                            <i class="bi bi-cash-stack"></i> Ödeme Yap
                        </a>
                    <?php endif; ?>
                    <a href="borc_detay.php?id=<?= $fatura_id ?>" class="btn btn-info btn-sm"><i class="bi bi-info-circle"></i> İşlem Detayı</a>
                    <a href="fatura_goruntule_pdf.php?id=<?= $fatura_id ?>&tur=<?= $fatura_turu ?>" target="_blank" class="btn btn-danger btn-sm"><i class="bi bi-file-earmark-pdf"></i> <?= __("download_pdf") ?></a>
                    <a href="borc_duzenle.php?id=<?= $fatura_id ?>" class="btn btn-warning btn-sm"><i class="bi bi-pencil"></i> <?= __("edit") ?></a>
                    <button onclick="window.print()" class="btn btn-secondary btn-sm"><i class="bi bi-printer"></i> <?= __("print") ?></button>
                    <a href="<?= $geri_don_url ?>" class="btn btn-primary btn-sm"><i class="bi bi-arrow-left"></i> <?= __("back") ?></a>
                </div>
            </div>
            <div class="card-body p-lg-5">
                <!-- Fatura Başlığı -->
                <div class="fatura-header row align-items-center">
                    <div class="col-md-6">
                        <h1 class="h3"><?= strtoupper(__('invoice')) ?></h1>
                        <p class="text-muted mb-0"><?= __('invoice_number') ?>: #<?= str_pad($fatura['id'], 6, '0', STR_PAD_LEFT) ?></p>
                    </div>
                    <div class="col-md-6 text-md-end">
                        <?php if (!empty($firma['logo_yolu']) && file_exists(__DIR__ . '/../' . $firma['logo_yolu'])): ?>
                            <img src="../<?= temizle($firma['logo_yolu']) ?>" alt="Firma Logosu" style="max-height: 60px;" class="mb-2">
                        <?php endif; ?>
                        <p class="mb-0"><strong><?= temizle($firma['sirket_adi']) ?></strong></p>
                        <p class="text-muted small"><?= __('tax_office') ?>: <?= temizle($firma['vergi_dairesi']) ?> - <?= __('tax_number') ?>: <?= temizle($firma['vergi_no']) ?></p>
                    </div>
                </div>

                <!-- Fatura Bilgileri -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <h5><?= temizle($cari_etiket) ?> <?= __('company_info') ?>:</h5>
                        <p class="mb-1"><strong><?= temizle($cari['ad_soyad']) ?></strong></p>
                        <p class="mb-1"><?= nl2br(temizle($cari['adres'] ?? __('address'))) ?></p>
                        <p class="mb-1"><i class="bi bi-telephone-fill me-2"></i><?= temizle($cari['telefon'] ?? __('phone')) ?></p>
                    </div>
                    <div class="col-md-6 text-md-end">
                        <p class="mb-1"><strong><?= __('invoice_date') ?>:</strong> <?= date('d.m.Y', strtotime($fatura['tarih'])) ?></p>
                        <?php if ($fatura['vade_tarihi']): ?>
                            <p class="mb-1"><strong><?= __('due_date') ?>:</strong> <?= date('d.m.Y', strtotime($fatura['vade_tarihi'])) ?></p>
                        <?php endif; ?>
                        <p class="mb-1"><strong><?= __('payment_status') ?>:</strong>
                            <?php if (($fatura['durum'] ?? '') === 'odendi'): ?>
                                <span class="badge bg-success fs-6"><?= strtoupper(__('paid')) ?></span>
                            <?php elseif (($fatura['durum'] ?? '') === 'kismen_odendi'): ?>
                                <span class="badge bg-warning text-dark fs-6"><?= strtoupper(__('partially_paid')) ?></span>
                            <?php else: ?>
                                <span class="badge bg-danger fs-6"><?= strtoupper(__('unpaid')) ?></span>
                            <?php endif; ?>
                        </p>
                        <form class="d-inline-block mt-2" method="post" action="fatura_goruntule.php?id=<?= $fatura_id ?>&tur=<?= $fatura_turu ?>">
                            <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                            <input type="hidden" name="islem" value="odeme_durumu_guncelle">
                            <div class="row g-2 align-items-center justify-content-end">
                                <div class="col-auto">
                                    <select name="yeni_durum" id="yeni_durum" class="form-select form-select-sm">
                                        <option value="odenmedi" <?= ($fatura['durum'] === 'odenmedi' ? 'selected' : '') ?>><?= __('unpaid') ?></option>
                                        <option value="kismen_odendi" <?= ($fatura['durum'] === 'kismen_odendi' ? 'selected' : '') ?>><?= __('partially_paid') ?></option>
                                        <option value="odendi" <?= ($fatura['durum'] === 'odendi' || $kalan_tutar <= 0.01 ? 'selected' : '') ?>><?= __('paid') ?></option>
                                    </select>
                                </div>
                                <div class="col-auto">
                                    <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-check2-circle"></i> <?= __('save') ?></button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <?php if ($fatura['stoklu_islem'] == '0' && !empty($fatura['aciklama'])): ?>
                <div class="mb-4">
                    <div class="card shadow-sm rounded-3 border-0">
                        <div class="card-header bg-primary text-white fw-bold py-2">
                            <i class="bi bi-info-circle me-2"></i><?= __('description_items') ?>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive mb-0">
                                <table class="table table-sm table-bordered table-hover align-middle mb-0">
                                    <thead class="table-primary">
                                        <tr>
                                            <th class="text-center" style="width:40px;">#</th>
                                            <th><?= __('description') ?></th>
                                            <th class="text-end" style="width:120px;"><?= __('amount') ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $satirlar = preg_split('/\r\n|\r|\n/', $fatura['aciklama']);
                                        $num = 1; $bos = true;
                                        foreach ($satirlar as $satir) {
                                            $satir = trim($satir);
                                            if ($satir === '') continue;
                                            $aciklama = $satir;
                                            $tutar = '';
                                            if (preg_match('/^(.*)\(([^)]+)\)$/u', $satir, $parcalar)) {
                                                $aciklama = trim($parcalar[1]);
                                                $tutar = trim($parcalar[2]);
                                            }
                                            echo '<tr>';
                                            echo '<td class="text-center">' . ($num++) . '</td>';
                                            echo '<td>' . temizle($aciklama) . '</td>';
                                            echo '<td class="text-end">' . temizle($tutar) . '</td>';
                                            echo '</tr>';
                                            $bos = false;
                                        }
                                        if ($bos) {
                                            echo '<tr><td colspan="3" class="text-center text-muted">'.__('no_description_items').'</td></tr>';
                                        }
                                        ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Ürünler Tablosu -->
                <?php if ($fatura['stoklu_islem'] == '1'): ?>
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th scope="col">#</th>
                                <th scope="col"><?= __('product_name') ?></th>
                                <th scope="col" class="text-end"><?= __('quantity') ?></th>
                                <th scope="col" class="text-end"><?= __('unit_price') ?></th>
                                <th scope="col" class="text-end"><?= __('vat_amount') ?></th>
                                <th scope="col" class="text-end"><?= __('amount') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            foreach ($detaylar as $index => $detay): 
                                $tutar = $detay['miktar'] * $detay['birim_fiyat'];
                                // Calculate total amount based on currency
                                if ($detay['urun_para_birimi'] === $paraBirimi || 
                                    ($detay['urun_para_birimi'] === 'TRY' && $paraBirimi === 'TL') || 
                                    ($detay['urun_para_birimi'] === 'TL' && $paraBirimi === 'TRY')) {
                                    // Same currency, just add KDV
                                    $toplamTutar = $tutar + $detay['kdv_tutari'];
                                } else {
                                    // Different currency, will be handled in the display logic
                                    $toplamTutar = $tutar;
                                }
                            ?>
                            <tr>
                                <th scope="row"><?= $index + 1 ?></th>
                                <td><?= temizle($detay['urun_adi']) ?></td>
                                <td class="text-end"><?= rtrim(rtrim(number_format($detay['miktar'], 2, ',', '.'), '0'), ',') ?> <?= temizle($detay['birim']) ?></td>
                                <td class="text-end">
                                    <?php 
                                    // Get the product's original currency and format it
                                    $urunParaBirimi = $detay['urun_para_birimi'] === 'TRY' ? 'TL' : $detay['urun_para_birimi'];
                                    $birimFiyat = $detay['birim_fiyat'];
                                    
                                    // Display the original price in the product's currency
                                    echo number_format($birimFiyat, 2, ',', '.') . ' ' . $urunParaBirimi;
                                    
                                    // If the product's currency is different from the invoice currency, show the converted amount
                                    if ($urunParaBirimi !== $paraBirimi) {
                                        // Get the latest exchange rate from the database
                                        $stmt_kur = $db->prepare("
                                            SELECT alis, satis FROM doviz_kurlari 
                                            WHERE para_birimi = ? 
                                            ORDER BY guncelleme_tarihi DESC 
                                            LIMIT 1
                                        ");
                                        $stmt_kur->execute([$detay['urun_para_birimi']]);
                                        $doviz_kuru = $stmt_kur->fetch(PDO::FETCH_ASSOC);
                                        
                                        // If exchange rate is found, calculate and show the converted amount
                                        if ($doviz_kuru) {
                                            // Use 'satis' (sell rate) for purchases, 'alis' (buy rate) for sales
                                            $kur = ($fatura_turu == 'satis') ? (float)$doviz_kuru['satis'] : (float)$doviz_kuru['alis'];
                                            $cevrilmisFiyat = $birimFiyat * $kur;
                                            echo '<br><small class="text-muted">(' . number_format($cevrilmisFiyat, 2, ',', '.') . ' ' . $paraBirimi . ')</small>';
                                        } else {
                                            // If no exchange rate is found, just show the original amount with a note
                                            echo '<br><small class="text-danger">(' . __('exchange_rate_not_found') . ')</small>';
                                        }
                                    }
                                    ?>
                                </td>
                                <td class="text-end">
                                    <?= number_format($detay['kdv_tutari'], 2, ',', '.') ?> <?= $paraBirimi ?>
                                </td>
                                <td class="text-end">
                                    <?php 
                                    // For the total amount, we'll always show it in the invoice currency
                                    // If the product's currency is different, we need to convert the base amount and then add KDV
                                    if ($detay['urun_para_birimi'] === $paraBirimi || ($detay['urun_para_birimi'] === 'TRY' && $paraBirimi === 'TL') || ($detay['urun_para_birimi'] === 'TL' && $paraBirimi === 'TRY')) {
                                        // Same currency, just add KDV
                                        $toplamTutar = $tutar + $detay['kdv_tutari'];
                                        echo number_format($toplamTutar, 2, ',', '.') . ' ' . $paraBirimi;
                                    } else {
                                        // Different currency, get the exchange rate
                                        $stmt_kur = $db->prepare("
                                            SELECT alis, satis FROM doviz_kurlari 
                                            WHERE para_birimi = ? 
                                            ORDER BY guncelleme_tarihi DESC 
                                            LIMIT 1
                                        ");
                                        $stmt_kur->execute([$detay['urun_para_birimi']]);
                                        $doviz_kuru = $stmt_kur->fetch(PDO::FETCH_ASSOC);
                                        
                                        if ($doviz_kuru) {
                                            // Use 'satis' (sell rate) for purchases, 'alis' (buy rate) for sales
                                            $kur = ($fatura_turu == 'satis') ? (float)$doviz_kuru['satis'] : (float)$doviz_kuru['alis'];
                                            
                                            // Convert the base amount to invoice currency
                                            $cevrilmisTutar = $tutar * $kur;
                                            
                                            // Add KDV (which is already in the invoice currency)
                                            $toplamTutar = $cevrilmisTutar + $detay['kdv_tutari'];
                                            
                                            echo number_format($toplamTutar, 2, ',', '.') . ' ' . $paraBirimi;
                                            echo '<br><small class="text-muted">(' . number_format($tutar, 2, ',', '.') . ' ' . $detay['urun_para_birimi'] . ' + KDV)</small>';
                                        } else {
                                            // If no exchange rate is found, show the original amount with a note
                                            $toplamTutar = $tutar + $detay['kdv_tutari']; // Use original amount + KDV as fallback
                                            echo number_format($toplamTutar, 2, ',', '.') . ' ' . $detay['urun_para_birimi'];
                                            echo '<br><small class="text-danger">(' . __('exchange_rate_not_found') . ')</small>';
                                        }
                                    }
                                    ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>

                <?php
                // Check if we should show product quantities
                $sirket_id = $_SESSION['aktif_sirket_id'] ?? 0;
                $show_quantities = (int)get_site_setting($db, 'fatura_urun_adetleri_goster', 1, $sirket_id);
                if ($show_quantities && !empty($detaylar)) {
                    $toplam_urun_sayisi = array_sum(array_column($detaylar, 'miktar'));
                    echo '<div class="p-2 bg-white rounded">';
                    echo '<i class="bi bi-box-seam me-2"></i> ';
                    echo '<strong>Toplam ' . number_format($toplam_urun_sayisi, 2, ',', '.') . ' adet ürün bulunmaktadır.</strong>';
                    echo '</div>';
                }
                ?>

                <div class="row justify-content-end mt-4">
                    <div class="col-md-6">
                        <table class="table table-sm totals-table">
                            <tbody>
                                <tr>
                                    <th class="text-end"><?= __('subtotal') ?>:</th>
                                    <td class="text-end"><?= number_format($ara_toplam, 2, ',', '.') ?> <?= $paraBirimi ?></td>
                                </tr>
                                <tr>
                                    <th class="text-end"><?= __('total_vat') ?>:</th>
                                    <td class="text-end"><?= number_format($toplam_kdv, 2, ',', '.') ?> <?= $paraBirimi ?></td>
                                </tr>
                                <?php if ($indirim > 0): ?>
                                <tr>
                                    <th class="text-end text-danger"><?= __('discount') ?>:</th>
                                    <td class="text-end text-danger">-<?= number_format($indirim, 2, ',', '.') ?> <?= $paraBirimi ?></td>
                                </tr>
                                <?php endif; ?>
                                <tr class="fw-bold">
                                    <th class="text-end border-top"><?= __('total_amount') ?>:</th>
                                    <td class="text-end border-top fs-5"><?= number_format($genel_toplam, 2, ',', '.') ?> <?= $paraBirimi ?></td>
                                </tr>
                                <tr>
                                    <th class="text-end text-success"><?= __('paid_amount') ?>:</th>
                                    <td class="text-end text-success"><?= number_format($odenen_tutar, 2, ',', '.') ?> <?= $paraBirimi ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Açıklama ve Footer -->
                <div class="fatura-footer">
                    <p class="text-center text-muted small"><?= __('generated_by') ?></p>
                </div>
            </div>
        </div>
    </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'; ?>
    <script>
        // Print functionality
        document.getElementById('printBtn').addEventListener('click', function() {
            window.print();
        });
    </script>
  </body>
</html>
