<?php
// Output buffering baÅŸlat - PDF Ã¶ncesi hiÃ§bir Ã§Ä±ktÄ± olmasÄ±n
ob_start();

// TEST SCRIPT BAÅLANGICI
try {
    require_once __DIR__ . '/../includes/config.php';
    require_once('tcpdf/tcpdf.php');

// Yetki kontrolÃ¼
yetkili_mi();

// BorÃ§ ID'sini al
$borc_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$borc_id) {
    die('GeÃ§ersiz borÃ§ ID');
}

    // BorÃ§ bilgisini Ã§ek
    $stmt = $db->prepare("SELECT b.*, c.ad_soyad AS cari_adi FROM borclar b LEFT JOIN cariler c ON b.cari_id = c.id WHERE b.id = ? AND b.sirket_id = ?");
    $stmt->execute([$borc_id, $aktif_sirket_id]);
    $borc = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$borc) {
        ob_end_clean();
        die('BorÃ§ bulunamadÄ±.');
    }

    // Ã–demeleri ve kalan tutarÄ± hesapla
    $stmt_hareket = $db->prepare("SELECT hh.*, h.hesap_adi FROM hesap_hareketleri hh JOIN hesaplar h ON hh.hesap_id = h.id WHERE hh.borc_id = ? AND hh.sirket_id = ? ORDER BY hh.tarih ASC");
    $stmt_hareket->execute([$borc_id, $aktif_sirket_id]);
    $hareketler = $stmt_hareket->fetchAll(PDO::FETCH_ASSOC);

    $islem_turu = $borc['tur'];
    $hareket_tur = ($islem_turu === 'alis') ? 'cikis' : 'giris';
    $stmt_odenen = $db->prepare("SELECT SUM(tutar) FROM hesap_hareketleri WHERE borc_id = ? AND sirket_id = ? AND tur = ?");
    $stmt_odenen->execute([$borc_id, $aktif_sirket_id, $hareket_tur]);
    $odenen_tutar = (float) $stmt_odenen->fetchColumn();
    $kalan_tutar = $borc['tutar'] - $odenen_tutar;

    // Buffer'Ä± temizle - PDF Ã§Ä±ktÄ±sÄ±ndan Ã¶nce
    ob_end_clean();

} catch (Exception $e) {
    ob_end_clean();
    die('Hata: ' . $e->getMessage());
}

// Extend the TCPDF class to create custom Header and Footer
class MYPDF extends TCPDF {
    private $sirket_adi;
    private $fatura_no;
    private $fatura_tarihi;

    public function setInvoiceDetails($sirket_adi, $fatura_no, $fatura_tarihi) {
        $this->sirket_adi = $sirket_adi;
        $this->fatura_no = $fatura_no;
        $this->fatura_tarihi = $fatura_tarihi;
    }

    //Page header
    public function Header() {
        $this->SetY(10);
        
        // Company logo/name on the left with background
        $this->SetFont('dejavusans', 'B', 16);
        $this->SetTextColor(255, 255, 255); // White text
        $this->SetFillColor(88, 103, 221); // Blue background
        $this->Cell(60, 12, 'Brand', 0, 0, 'C', true); // true for fill
        
        // Document info on the right
        $this->SetFont('dejavusans', '', 10);
        $this->SetTextColor(128, 128, 128);
        $this->SetXY($this->GetPageWidth() - 80, 12);
        $this->Cell(30, 4, 'Tarih', 0, 0, 'R');
        $this->SetXY($this->GetPageWidth() - 80, 16);
        $this->Cell(30, 4, 'Fatura #', 0, 0, 'R');
        
        $this->SetFont('dejavusans', 'B', 10);
        $this->SetTextColor(88, 103, 221);
        $this->SetXY($this->GetPageWidth() - 45, 12);
        $this->Cell(30, 4, $this->fatura_tarihi, 0, 0, 'R');
        $this->SetXY($this->GetPageWidth() - 45, 16);
        $this->Cell(30, 4, 'FAT-' . str_pad($this->fatura_no, 5, '0', STR_PAD_LEFT), 0, 0, 'R');
        
        $this->SetY(28);
    }

    // Page footer
    public function Footer() {
        $this->SetY(-20);
        $this->SetFont('dejavusans', '', 9);
        $this->SetTextColor(128, 128, 128);
        $this->Cell(0, 10, "Supplier Company | info@company.com | +1-202-555-0106", 0, 0, 'C');
    }
}

// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Odjoo');
$pdf->SetTitle('Fatura - ' . $borc['id']);
$pdf->SetSubject('Fatura DetayÄ±');

$sirket_adi = $_SESSION['sirket_adi'] ?? 'Brand';
$fatura_tarihi_formatted = date('M d, Y', strtotime($borc['tarih']));

$pdf->setInvoiceDetails($sirket_adi, $borc['id'], $fatura_tarihi_formatted);

// set margins
$pdf->SetMargins(15, 45, 15);
$pdf->SetHeaderMargin(10);
$pdf->SetFooterMargin(15);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, 25);

// add a page
$pdf->AddPage();

// set font before writing html
$pdf->SetFont('dejavusans', '', 10);

// Format values
$tutar_formatted = number_format($borc['tutar'], 2, ',', '.');
$odenen_tutar_formatted = number_format($odenen_tutar, 2, ',', '.');
$kalan_tutar_formatted = number_format($kalan_tutar, 2, ',', '.');

// Get real company information from database
$stmt_sirket = $db->prepare("SELECT * FROM sirketler WHERE id = ?");
$stmt_sirket->execute([$_SESSION['aktif_sirket_id']]);
$sirket_bilgileri = $stmt_sirket->fetch(PDO::FETCH_ASSOC);

// Get currency symbol
$para_birimi_sembolu = getParaBirimiSembolu($sirket_bilgileri['para_birimi'] ?? 'TRY');

// Get customer information
$stmt_musteri = $db->prepare("SELECT * FROM cariler WHERE id = ?");
$stmt_musteri->execute([$borc['cari_id']]);
$musteri_bilgileri = $stmt_musteri->fetch(PDO::FETCH_ASSOC);

// Calculate VAT and totals (using Turkish VAT rate 18%)
$net_total = $borc['tutar'];
$vat_rate = 0.18;
$vat_amount = $net_total * $vat_rate;
$total_with_vat = $net_total + $vat_amount;

$html = <<<EOD
<style>
    body { 
        font-family: dejavusans; 
        margin: 0; 
        padding: 0; 
        background-color: #ffffff; 
        color: #333333; 
    }
    .container { 
        padding: 20px 0; 
    }
    .company-section {
        margin-bottom: 20px; /* Reduced space */
    }
    .company-table {
        width: 100%;
        border-collapse: collapse;
    }
    .supplier-info {
        width: 50%;
        vertical-align: top;
    }
    .customer-info {
        width: 50%;
        text-align: right;
        vertical-align: top;
    }
    .company-name {
        font-size: 14px;
        font-weight: bold;
        color: #333333;
        margin-bottom: 5px;
    }
    .company-details {
        font-size: 10px;
        color: #666666;
        line-height: 1.4;
    }
    .clear {
        clear: both;
    }
    .items-table {
        width: 100%;
        border-collapse: collapse;
        margin: 30px 0;
        font-size: 10px;
    }
    .items-table th {
        background-color: #f8f9fa;
        color: #666666;
        padding: 12px 8px;
        text-align: left;
        font-size: 10px;
        font-weight: normal;
        border-bottom: 1px solid #e9ecef;
    }
    .items-table td {
        padding: 12px 8px;
        border-bottom: 1px solid #f1f3f4;
        font-size: 10px;
        vertical-align: top;
    }
    .item-number {
        color: #666666;
        text-align: center;
        width: 8%;
    }
    .item-details {
        width: 42%;
    }
    .item-price, .item-qty, .item-vat, .item-subtotal, .item-total {
        text-align: right;
        width: 10%;
    }
    .product-name {
        font-weight: normal;
        color: #333333;
        margin-bottom: 2px;
    }
    .totals-section {
        margin-top: 40px;
        float: right;
        width: 250px;
    }
    .totals-row {
        padding: 8px 0;
        font-size: 11px;
    }
    .totals-label {
        color: #666666;
        text-align: right;
        padding-right: 20px;
    }
    .totals-value {
        text-align: right;
        font-weight: bold;
        color: #333333;
    }
    .net-total {
        border-bottom: 1px solid #e9ecef;
        padding-bottom: 8px;
        margin-bottom: 8px;
    }
    .vat-total {
        border-bottom: 1px solid #e9ecef;
        padding-bottom: 8px;
        margin-bottom: 8px;
    }
    .grand-total {
        background-color: #5865f2;
        color: white;
        padding: 12px;
        font-size: 12px;
        font-weight: bold;
        text-align: center;
    }
    .payment-section {
        margin-top: 50px;
        clear: both;
    }
    .payment-title {
        font-size: 12px;
        font-weight: bold;
        color: #5865f2;
        margin-bottom: 10px;
    }
    .payment-details {
        font-size: 10px;
        color: #666666;
        line-height: 1.5;
    }
    .notes-section {
        margin-top: 30px;
    }
    .notes-title {
        font-size: 12px;
        font-weight: bold;
        color: #333333;
        margin-bottom: 10px;
    }
    .notes-text {
        font-size: 10px;
        color: #666666;
        line-height: 1.5;
        font-style: italic;
    }
</style>

<div class="container">
    <div class="company-section">
        <table class="company-table">
            <tr>
                <td class="supplier-info">
                    <div class="company-name">{$sirket_bilgileri['sirket_adi']}</div>
                    <div class="company-details">
                        Vergi No: {$sirket_bilgileri['vergi_no']}<br>
                        Vergi Dairesi: {$sirket_bilgileri['vergi_dairesi']}<br>
                        {$sirket_bilgileri['adres']}<br>
                        Tel: {$sirket_bilgileri['telefon']}<br>
                        E-posta: {$sirket_bilgileri['email']}
                    </div>
                </td>
                <td class="customer-info">
                    <div class="company-name">MÃ¼ÅŸteri Bilgileri</div>
                    <div class="company-details">
                        {$musteri_bilgileri['ad_soyad']}<br>
                        Tel: {$musteri_bilgileri['telefon']}<br>
                        {$musteri_bilgileri['adres']}
                    </div>
                </td>
            </tr>
        </table>
    </div>
    
    <div style="margin: 20px 0; text-align: center;">
        <h3 style="font-size: 14px; color: #333; margin-bottom: 5px;"><?php echo $borc['tur'] == 'alis' ? 'Alis' : 'Satis'; ?> Islemi - #<?php echo $borc['id']; ?></h3>
        <p style="font-size: 12px; color: #666; margin: 0;"><?php echo $borc['aciklama']; ?></p>
        <p style="font-size: 11px; color: #666; margin-top: 5px;">Islem Tarihi: <?php echo date('d.m.Y', strtotime($borc['tarih'])); ?></p>
        <p style="font-size: 11px; color: #666; margin-top: 2px;">Vade Tarihi: <?php echo !empty($borc['vade_tarihi']) ? date('d.m.Y', strtotime($borc['vade_tarihi'])) : 'Belirtilmemis'; ?></p>
        <?php
        // Durum bilgisi
        $durum_text = '';
        $durum_color = '';
        
        if ($borc['durum'] == 'odendi') {
            $durum_text = 'Odendi';
            $durum_color = '#198754'; // Yesil
        } elseif ($kalan_tutar <= 0.01) {
            $durum_text = 'Odendi';
            $durum_color = '#198754'; // Yesil
        } elseif ($odenen_tutar > 0) {
            $durum_text = 'Kismen Odendi';
            $durum_color = '#fd7e14'; // Turuncu
        } else {
            $durum_text = 'Odenmedi';
            $durum_color = '#dc3545'; // Kirmizi
        }
        ?>
        <div style="margin-top: 10px;">
            <span style="display: inline-block; padding: 5px 10px; background-color: <?php echo $durum_color; ?>; color: white; border-radius: 4px; font-size: 12px; font-weight: bold;">
                <?php echo $durum_text; ?>
            </span>
        </div>
    </div>

    <h4 style="font-size: 12px; color: #5865f2; margin: 10px 0;">Bu Islemle Ilgili Hesap Hareketleri (Odemeler/Tahsilatlar)</h4>
    <table class="items-table">
        <thead>
            <tr>
                <th class="item-number">Tarih</th>
                <th class="item-details">Hesap</th>
                <th class="item-price">Tur</th>
                <th class="item-qty">Tutar</th>
                <th class="item-vat">Aciklama</th>
            </tr>
        </thead>
        <tbody>
EOD;

// Add items based on debt details
if (!empty($hareketler)) {
    foreach ($hareketler as $hareket) {
        $html .= '<tr>';
        $html .= '<td class="item-number">' . date('d.m.Y H:i', strtotime($hareket['tarih'])) . '</td>';
        $html .= '<td class="item-details">' . temizle($hareket['hesap_adi']) . '</td>';
        
        // Tur (Giris/Cikis)
        $html .= '<td class="item-price">';
        if ($hareket['tur'] == 'giris') {
            $html .= '<span style="color: #198754; font-weight: bold;">Giris</span>';
        } elseif ($hareket['tur'] == 'cikis') {
            $html .= '<span style="color: #dc3545; font-weight: bold;">Cikis</span>';
        }
        $html .= '</td>';
        
        // Tutar
        $html .= '<td class="item-qty" style="font-weight: bold; ' . ($hareket['tur'] == 'giris' ? 'color: #198754;' : 'color: #dc3545;') . '">';
        $html .= ($hareket['tur'] == 'giris' ? '+' : '-') . number_format($hareket['tutar'], 2, ',', '.') . ' ' . $para_birimi_sembolu;
        $html .= '</td>';
        
        // AÃ§Ä±klama
        $html .= '<td class="item-vat">' . temizle($hareket['aciklama']) . '</td>';
        $html .= '</tr>';
    }
} else {
    $html .= '<tr>';
    $html .= '<td colspan="5" style="text-align: center; padding: 20px; color: #6c757d;">Bu islemle dogrudan iliskili bir odeme veya tahsilat kaydi bulunmamaktadir.</td>';
    $html .= '</tr>';
}

$html .= '</tbody>
    </table>

    <div class="totals-section">
        <div class="totals-row net-total">
            <table width="100%">
                <tr>
                    <td class="totals-label">Toplam Tutar:</td>
                    <td class="totals-value">' . $tutar_formatted . ' ' . $para_birimi_sembolu . '</td>
                </tr>
            </table>
        </div>
        <div class="totals-row vat-total">
            <table width="100%">
                <tr>
                    <td class="totals-label">Ã–denen Tutar:</td>
                    <td class="totals-value">' . $odenen_tutar_formatted . ' ' . $para_birimi_sembolu . '</td>
                </tr>
            </table>
        </div>
        <div class="grand-total">
            Kalan Tutar: ' . $kalan_tutar_formatted . ' ' . $para_birimi_sembolu . '
        </div>
    </div>
    <div class="clear"></div>

   
</div>';

// HTML'i PDF'e yazdÄ±r
$pdf->writeHTML($html, true, false, true, false, '');

// Fatura resmini ekle
if (!empty($borc['fatura_resmi'])) {
    $resim_yolu = __DIR__ . '/../uploads/' . $borc['fatura_resmi'];
    if (file_exists($resim_yolu)) {
        $pdf->AddPage();
        $pdf->SetFont('dejavusans', 'B', 12);
        $pdf->Cell(0, 10, 'Fatura Resmi', 0, 1, 'L');
        $pdf->Image($resim_yolu, 15, $pdf->GetY(), 180, 0, '', '', 'T', false, 300, '', false, false, 0, false, false, false);
    }
}

//Close and output PDF document
$filename = 'Fatura-' . preg_replace('/[^A-Za-z0-9\-]/', '', $borc['cari_adi']) . '-' . $borc['id'] . '.pdf';
$pdf->Output($filename, 'I');

exit;
?>
