<?php
session_start();
if (empty($_SESSION['admin_logged_in'])) { http_response_code(403); exit('Yetkisiz erişim'); }
require_once __DIR__ . '/db.php';

$id = (int)($_GET['id'] ?? 0);
if (!$id) exit('Geçersiz ID');

$db = getDB();
$r  = $db->prepare("SELECT * FROM reservations WHERE id=:id");
$r->bindValue(':id', $id);
$rez = $r->execute()->fetchArray(SQLITE3_ASSOC);
if (!$rez) exit('Rezervasyon bulunamadı');

$settings = [];
$res = $db->query("SELECT * FROM settings");
while ($row = $res->fetchArray(SQLITE3_ASSOC)) $settings[$row['key']] = $row['value'];

// Fatura hesaplamaları
$kdv_oran   = 20;
$net_tutar  = $rez['total_price'] ?? 0;
$kdv_tutar  = round($net_tutar * $kdv_oran / 100);
$toplam     = $net_tutar + $kdv_tutar;
$kapora     = 5000;
$kdv_kapora = round($kapora * $kdv_oran / 100);
$kapora_toplam = $kapora + $kdv_kapora;

$fatura_no  = 'FAT-' . date('Y') . '-' . str_pad($id, 5, '0', STR_PAD_LEFT);
$fatura_tar = date('d.m.Y');
$rez_no     = $rez['rezervasyon_no'] ?: ('RES-' . str_pad($id, 6, '0', STR_PAD_LEFT));

// QR kod verisi (e-arşiv simülasyonu)
$qr_data = urlencode("FATURA:{$fatura_no}|REZ:{$rez_no}|MUSTERI:{$rez['customer_name']}|TC:{$rez['tc_no']}|TUTAR:{$toplam}TL|TARIH:{$fatura_tar}");
$qr_url  = "https://api.qrserver.com/v1/create-qr-code/?size=120x120&data={$qr_data}";

$days = 1;
if ($rez['pickup_date'] && $rez['dropoff_date']) {
    $days = max(1, (int)ceil((strtotime($rez['dropoff_date']) - strtotime($rez['pickup_date'])) / 86400));
}
$car_res = $db->prepare("SELECT daily_price FROM cars WHERE id=:id");
$car_res->bindValue(':id', $rez['car_id']);
$car_row = $car_res->execute()->fetchArray(SQLITE3_ASSOC);
$daily   = $car_row ? $car_row['daily_price'] : ($net_tutar > 0 ? round($net_tutar / $days) : 0);
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="utf-8">
<title>E-Arşiv Fatura - <?= htmlspecialchars($fatura_no) ?></title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: Arial, sans-serif; font-size: 12px; color: #222; background: #fff; }
  .page { width: 210mm; min-height: 297mm; margin: 0 auto; padding: 14mm 14mm 10mm; }
  .header { display: flex; justify-content: space-between; align-items: flex-start; border-bottom: 3px solid #c0392b; padding-bottom: 12px; margin-bottom: 16px; }
  .logo-area h1 { font-size: 22px; color: #c0392b; font-weight: 900; letter-spacing: 1px; }
  .logo-area p { font-size: 10px; color: #666; margin-top: 2px; }
  .earşiv-badge { background: #c0392b; color: #fff; padding: 6px 14px; border-radius: 4px; font-size: 11px; font-weight: 700; text-align: center; }
  .earşiv-badge small { display: block; font-size: 9px; font-weight: 400; margin-top: 2px; }
  .fatura-bilgi { display: flex; justify-content: space-between; margin-bottom: 16px; gap: 16px; }
  .bilgi-kutu { flex: 1; background: #f8f9fa; border: 1px solid #eee; border-radius: 6px; padding: 10px 14px; }
  .bilgi-kutu h4 { font-size: 10px; color: #c0392b; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px; border-bottom: 1px solid #eee; padding-bottom: 4px; }
  .bilgi-kutu p { font-size: 11px; line-height: 1.8; color: #444; }
  .bilgi-kutu strong { color: #222; }
  table.kalemler { width: 100%; border-collapse: collapse; margin-bottom: 16px; }
  table.kalemler th { background: #c0392b; color: #fff; padding: 8px 10px; font-size: 11px; text-align: left; }
  table.kalemler td { padding: 8px 10px; border-bottom: 1px solid #eee; font-size: 11px; }
  table.kalemler tr:nth-child(even) td { background: #fafafa; }
  .toplam-tablo { width: 280px; margin-left: auto; border-collapse: collapse; }
  .toplam-tablo td { padding: 6px 10px; font-size: 11px; border-bottom: 1px solid #eee; }
  .toplam-tablo .toplam-satir td { background: #c0392b; color: #fff; font-weight: 700; font-size: 13px; }
  .kapora-satir td { background: #fff3cd; color: #856404; font-weight: 600; }
  .footer-area { margin-top: 20px; border-top: 2px solid #eee; padding-top: 12px; display: flex; justify-content: space-between; align-items: flex-end; }
  .qr-area { text-align: center; }
  .qr-area img { width: 100px; height: 100px; border: 2px solid #eee; border-radius: 4px; }
  .qr-area p { font-size: 9px; color: #888; margin-top: 4px; }
  .yasal-not { font-size: 9px; color: #888; max-width: 380px; line-height: 1.6; }
  .durum-badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 10px; font-weight: 700; }
  .durum-beklemede { background: #fff3cd; color: #856404; }
  .durum-onaylandi { background: #d1e7dd; color: #0f5132; }
  @media print {
    body { background: #fff; }
    .no-print { display: none !important; }
    .page { padding: 8mm; }
  }
</style>
</head>
<body>
<div class="no-print" style="background:#1a1a2e;padding:10px 20px;display:flex;gap:10px;align-items:center">
  <span style="color:#fff;font-size:.9rem">📄 E-Arşiv Fatura — <?= htmlspecialchars($fatura_no) ?></span>
  <button onclick="window.print()" style="background:#c0392b;color:#fff;border:none;padding:7px 18px;border-radius:5px;cursor:pointer;font-weight:700">🖨️ Yazdır / PDF İndir</button>
  <button onclick="window.close()" style="background:#555;color:#fff;border:none;padding:7px 14px;border-radius:5px;cursor:pointer">Kapat</button>
</div>

<div class="page">
  <div class="header">
    <div class="logo-area">
      <h1>AViS</h1>
      <p>Uygun Araç Kiralama Hizmetleri</p>
      <p>avisuygunarac.com | <?= htmlspecialchars($settings['whatsapp_number'] ?? '') ?></p>
    </div>
    <div style="text-align:right">
      <div class="earşiv-badge">
        📋 E-ARŞİV FATURA
        <small>Elektronik Arşiv Belgesi</small>
      </div>
      <p style="font-size:10px;color:#666;margin-top:8px">Fatura No: <strong><?= htmlspecialchars($fatura_no) ?></strong></p>
      <p style="font-size:10px;color:#666">Tarih: <strong><?= $fatura_tar ?></strong></p>
      <p style="font-size:10px;color:#666">Rez. No: <strong><?= htmlspecialchars($rez_no) ?></strong></p>
    </div>
  </div>

  <div class="fatura-bilgi">
    <div class="bilgi-kutu">
      <h4>Satıcı Bilgileri</h4>
      <p><strong>Avis Uygun Araç Kiralama</strong><br>
      Web: avisuygunarac.com<br>
      Tel: <?= htmlspecialchars($settings['whatsapp_number'] ?? '-') ?><br>
      Hizmet: Araç Kiralama</p>
    </div>
    <div class="bilgi-kutu">
      <h4>Müşteri Bilgileri</h4>
      <p><strong><?= htmlspecialchars($rez['customer_name']) ?></strong><br>
      TC Kimlik: <?= htmlspecialchars($rez['tc_no'] ?: '-') ?><br>
      Tel: <?= htmlspecialchars($rez['customer_phone']) ?><br>
      E-posta: <?= htmlspecialchars($rez['customer_email'] ?: '-') ?></p>
    </div>
    <div class="bilgi-kutu">
      <h4>Rezervasyon Bilgileri</h4>
      <p>Rez. No: <strong><?= htmlspecialchars($rez_no) ?></strong><br>
      Alış: <?= htmlspecialchars($rez['pickup_airport']) ?><br>
      İade: <?= htmlspecialchars($rez['dropoff_airport']) ?><br>
      Tarih: <?= $rez['pickup_date'] ?> → <?= $rez['dropoff_date'] ?><br>
      Süre: <?= $days ?> gün</p>
    </div>
  </div>

  <table class="kalemler">
    <thead>
      <tr><th>#</th><th>Hizmet Açıklaması</th><th>Birim</th><th>Miktar</th><th>Birim Fiyat</th><th>KDV %<?= $kdv_oran ?></th><th>Toplam</th></tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td><?= htmlspecialchars($rez['car_name']) ?> Araç Kiralama<br><small style="color:#888"><?= $rez['pickup_date'] ?> – <?= $rez['dropoff_date'] ?></small></td>
        <td>Gün</td>
        <td><?= $days ?></td>
        <td><?= number_format($daily, 0, ',', '.') ?> TL</td>
        <td><?= number_format($kdv_tutar, 0, ',', '.') ?> TL</td>
        <td><?= number_format($toplam, 0, ',', '.') ?> TL</td>
      </tr>
    </tbody>
  </table>

  <table class="toplam-tablo">
    <tr><td>Ara Toplam (KDV Hariç)</td><td style="text-align:right"><?= number_format($net_tutar, 0, ',', '.') ?> TL</td></tr>
    <tr><td>KDV (%<?= $kdv_oran ?>)</td><td style="text-align:right"><?= number_format($kdv_tutar, 0, ',', '.') ?> TL</td></tr>
    <tr class="toplam-satir"><td>GENEL TOPLAM</td><td style="text-align:right"><?= number_format($toplam, 0, ',', '.') ?> TL</td></tr>
    <tr class="kapora-satir"><td>Alınan Kapora</td><td style="text-align:right"><?= number_format($kapora_toplam, 0, ',', '.') ?> TL</td></tr>
    <tr><td style="color:#c0392b;font-weight:600">Kalan Bakiye (Teslimde)</td><td style="text-align:right;color:#c0392b;font-weight:600"><?= number_format($toplam - $kapora_toplam, 0, ',', '.') ?> TL</td></tr>
  </table>

  <div class="footer-area">
    <div class="yasal-not">
      <p>Bu belge elektronik ortamda düzenlenmiş e-arşiv faturadır.</p>
      <p>Fatura No: <?= htmlspecialchars($fatura_no) ?> | Düzenleme Tarihi: <?= $fatura_tar ?></p>
      <p style="margin-top:6px">Ödeme Yöntemi: <?= $rez['payment_method'] === 'havale' ? 'Havale/EFT' : 'Kredi Kartı' ?></p>
      <p>Durum: <span class="durum-badge durum-<?= $rez['status'] ?>"><?= $rez['status'] ?></span></p>
    </div>
    <div class="qr-area">
      <img src="<?= $qr_url ?>" alt="QR Kod">
      <p>E-Arşiv Doğrulama QR</p>
      <p><?= htmlspecialchars($fatura_no) ?></p>
    </div>
  </div>
</div>
</body>
</html>
