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

// 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;
    }
}

$teklif_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$teklif_id) {
    $_SESSION['hata'] = __("invalid_quote_id");
    header('Location: teklifler.php');
    exit();
}

try {
    // 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);
    if (!$firma) {
        throw new Exception(__("company_info_not_found"));
    }

    // Teklif ana bilgilerini çek
    $stmt_teklif = $db->prepare("
        SELECT t.*, c.ad_soyad as cari_adi, c.adres as cari_adres, c.telefon as cari_telefon,
               COALESCE(t.para_birimi, 'TRY') as para_birimi
        FROM teklifler t
        JOIN cariler c ON t.cari_id = c.id
        WHERE t.id = ?
    ");
    $stmt_teklif->execute([$teklif_id]);
    $teklif = $stmt_teklif->fetch(PDO::FETCH_ASSOC);

    if (!$teklif) {
        $_SESSION['hata'] = __("quote_not_found");
        header('Location: teklifler.php');
        exit();
    }

    // Teklif detaylarını (ürünleri) çek
    $stmt_detaylar = $db->prepare("
        SELECT td.*, u.urun_adi, u.birim, u.alis_para_birimi, u.satis_para_birimi
        FROM teklif_detaylari td
        JOIN urunler u ON td.urun_id = u.id
        WHERE td.teklif_id = ?
    ");
    $stmt_detaylar->execute([$teklif_id]);
    $detaylar = $stmt_detaylar->fetchAll(PDO::FETCH_ASSOC);

    // Toplamları hesapla
    $ara_toplam = $teklif['tutar'];
    $toplam_kdv = $teklif['toplam_kdv'];
    $indirim = $teklif['indirim_tutari'];
    $genel_toplam = $ara_toplam + $toplam_kdv - $indirim;

    // Teklifin stoklu mu stoksuz mu olduğunu belirle
    $is_stoksuz = empty($detaylar) && !empty($teklif['aciklama']);

} catch (Exception $e) {
    $_SESSION['hata'] = "Veri çekme hatası: " . $e->getMessage();
    header('Location: teklifler.php');
    exit();
}

$sayfa_baslik = __("quote_details") . " #" . str_pad($teklif['id'], 6, '0', STR_PAD_LEFT);
?>
<!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) ?></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; }
        }
        .teklif-header { border-bottom: 2px solid #dee2e6; padding-bottom: 1rem; margin-bottom: 2rem; }
        .teklif-footer { border-top: 2px solid #dee2e6; padding-top: 1rem; margin-top: 2rem; }
    </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-file-earmark-text-fill"></i> <?= temizle($sayfa_baslik) ?></h4>
                <div>
                    <a href="teklif_pdf.php?id=<?= $teklif_id ?>" class="btn btn-danger btn-sm"><i class="bi bi-file-earmark-pdf"></i> <?= __("download_pdf") ?></a>
                    <button onclick="window.print()" class="btn btn-secondary btn-sm"><i class="bi bi-printer"></i> <?= __("print") ?></button>
                    <a href="teklifler.php" class="btn btn-primary btn-sm"><i class="bi bi-arrow-left"></i> <?= __("back_to_quotes") ?></a>
                </div>
            </div>
            <div class="card-body p-lg-5">
                <!-- Header -->
                <div class="teklif-header row align-items-center">
                    <div class="col-md-6">
                        <?php if (!empty($firma['logo_yolu']) && file_exists(__DIR__ . '/../' . $firma['logo_yolu'])): ?>
                            <img src="../<?= temizle($firma['logo_yolu']) ?>" alt="<?= __("company_logo") ?>" style="max-height: 80px;" class="mb-2">
                        <?php endif; ?>
                        <h4 class="mb-0"><?= temizle($firma['sirket_adi']) ?></h4>
                        <p class="text-muted mb-0"><?= temizle($firma['adres']) ?></p>
                    </div>
                    <div class="col-md-6 text-md-end">
                        <h1 class="display-6 text-primary"><?= strtoupper(__('quote')) ?></h1>
                        <p class="mb-1"><strong><?= __("quote_number") ?>:</strong> #<?= str_pad($teklif['id'], 6, '0', STR_PAD_LEFT) ?></p>
                        <p class="mb-0"><strong><?= __("date") ?>:</strong> <?= date('d.m.Y', strtotime($teklif['teklif_tarihi'])) ?></p>
                    </div>
                </div>

                <!-- Bilgiler -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <h5><?= __("customer") ?>:</h5>
                        <p class="mb-1"><strong><?= temizle($teklif['cari_adi']) ?></strong></p>
                        <p class="mb-1"><?= nl2br(temizle($teklif['cari_adres'] ?? __('address_not_specified'))) ?></p>
                        <p class="mb-1"><i class="bi bi-telephone-fill me-2"></i><?= temizle($teklif['cari_telefon'] ?? __('no_phone')) ?></p>
                    </div>
                    <div class="col-md-6 text-md-end">
                         <h5><?= __("quote_information") ?>:</h5>
                         <p class="mb-1"><strong><?= __("quote_date") ?>:</strong> <?= date('d.m.Y', strtotime($teklif['teklif_tarihi'])) ?></p>
                         <?php if ($teklif['gecerlilik_tarihi']): ?>
                            <p class="mb-1"><strong><?= __("valid_until") ?>:</strong> <?= date('d.m.Y', strtotime($teklif['gecerlilik_tarihi'])) ?></p>
                         <?php endif; ?>
                    </div>
                </div>

                <!-- Ürünler Tablosu -->
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th scope="col">#</th>
                                <?php if ($is_stoksuz): ?>
                                    <th scope="col"><?= __("description") ?></th>
                                    <th scope="col" class="text-end"><?= __("amount") ?></th>
                                <?php else: ?>
                                    <th scope="col"><?= __("product_service_name") ?></th>
                                    <th scope="col" class="text-end"><?= __("quantity") ?></th>
                                    <th scope="col" class="text-end"><?= __("unit_price_original") ?></th>
                                    <th scope="col" class="text-end"><?= __("vat") ?> (%)</th>
                                    <th scope="col" class="text-end"><?= __("amount_quote_currency") ?></th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($is_stoksuz): // Stoksuz Teklif Kalemleri ?>
                                <?php
                                $satirlar = preg_split('/\r\n|\r|\n/', trim($teklif['aciklama']));
                                $num = 1;
                                foreach ($satirlar as $satir) {
                                    if (trim($satir) === '') continue;
                                    if (preg_match('/^(.*) \((.*)\)$/', $satir, $matches)) {
                                        $aciklama = trim($matches[1]);
                                        $tutar_str = trim($matches[2]);
                                        echo '<tr>';
                                        echo '<th scope="row">' . $num++ . '</th>';
                                        echo '<td>' . temizle($aciklama) . '</td>';
                                        echo '<td class="text-end">' . temizle($tutar_str) . '</td>';
                                        echo '</tr>';
                                    } else {
                                        echo '<tr><td colspan="3"><em>' . nl2br(temizle($satir)) . '</em></td></tr>';
                                    }
                                }
                                ?>
                            <?php elseif (!empty($detaylar)): // Stoklu Teklif Kalemleri ?>
                                <?php foreach ($detaylar as $index => $detay): ?>
                                <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"><?= number_format($detay['birim_fiyat'], 2, ',', '.') . ' ' . ($detay['satis_para_birimi'] ?? $teklif['para_birimi'] ?? 'TRY') ?></td>
                                    <td class="text-end"><?= rtrim(rtrim(number_format($detay['kdv_orani'], 2, ',', '.'), '0'), ',') ?>%</td>
                                    <td class="text-end"><?= number_format($detay['toplam_tutar'], 2, ',', '.') . ' ' . ($teklif['para_birimi'] ?? 'TRY') ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: // Kalem yoksa ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted"><?= __("no_quote_items") ?></td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Toplamlar -->
                <div class="row justify-content-end mt-4">
                    <div class="col-md-5">
                        <table class="table">
                            <tbody>
                                <tr>
                                    <th class="text-end"><?= __("subtotal") ?>:</th>
                                    <td class="text-end"><?= number_format($ara_toplam, 2, ',', '.') . ' ' . ($teklif['para_birimi'] ?? 'TRY') ?></td>
                                </tr>
                                <tr>
                                    <th class="text-end"><?= __("total_vat") ?>:</th>
                                    <td class="text-end"><?= number_format($toplam_kdv, 2, ',', '.') . ' ' . ($teklif['para_birimi'] ?? 'TRY') ?></td>
                                </tr>
                                <?php if ($indirim > 0): ?>
                                <tr>
                                    <th class="text-end"><?= __("discount") ?>:</th>
                                    <td class="text-end text-danger">-<?= number_format($indirim, 2, ',', '.') . ' ' . ($teklif['para_birimi'] ?? 'TRY') ?></td>
                                </tr>
                                <?php endif; ?>
                                <tr class="fw-bold fs-5 table-primary">
                                    <th class="text-end"><?= __("grand_total") ?>:</th>
                                    <td class="text-end"><?= number_format($genel_toplam, 2, ',', '.') . ' ' . ($teklif['para_birimi'] ?? 'TRY') ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Footer -->
                <div class="teklif-footer">
                    <p><strong><?= __("notes") ?>:</strong></p>
                    <ul>
                        <?php if (!$is_stoksuz && !empty($teklif['aciklama'])): ?>
                            <li><?= nl2br(temizle($teklif['aciklama'])) ?></li>
                        <?php endif; ?>
                        <li><?= str_replace(':currency', ($teklif['para_birimi'] ?? 'TRY'), __("price_currency_note")) ?></li>
                    </ul>
                    <p class="text-center text-muted small mt-4"><?= str_replace(':website', temizle($firma['web_sitesi']), __("generated_by_odjoo")) ?></p>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
