<?php
	$path="../../";
	include("../../map.php");
	$sqls=mysqli_query($conn, "select * from genel where ne='sablon' and t2='invoice'"); $rss=mysqli_fetch_assoc($sqls);
	$sql = mysqli_query($conn, "select * from t4 where id=".$_GET["id"].""); $rsf=mysqli_fetch_assoc($sql);
		$ftarih="".$rsf["s2"].".".$rsf["s3"].".".$rsf["s4"]."";
		$fno="".$rsf["t1"]."";
		$sqlm = mysqli_query($conn, "select * from t5 where id=".$rsf["s1"].""); $rsm=mysqli_fetch_assoc($sqlm);
		$jsi = json_decode($rsm["n17"], true);
		if($h5<>1){
			$fadres = "".$rsm["n5"]."<br>".$rsm["t4"]."";
		}else{
			$sqla=mysqli_query($conn, "select * from t1 where ne='adress' and t2='".$_SESSION['lang']."' and id=".$siparis["s11"].""); $adress=mysqli_fetch_assoc($sqla);
			$fadres .= "".$adress["n2"]." (".$adress["n1"].")<br>";
			$fadres .= "".$adress["n6"]." ".loc($adress["n3"])." / ".loc($adress["n4"])." / ".loc($adress["n5"])."";
		}
		$fcari=$rsm["id"];
		if($rsm["s5"]<>"0"){$fcisk=($rsm["s5"]+100)/100;}else{$fcisk=0;}

		function replaceVars($template, $data = []) {
			global $ftarih, $fno;
			$defaults = [
				"{idate}" => $ftarih,
				"{ino}"    => $fno
			];
			$data = array_merge($defaults, $data);
			$result = str_replace(array_keys($data), array_values($data), $template);
			echo $result; // ekrana bas
		}

?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Proforma Fatura (A4)</title>
  <!-- Bootstrap 5 CDN -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ENjdO4Dr2bkBIFxQpeoYz1H6k9FQq4/5n3z9Zl+Y5n1o6V9K5n8Wv+0U8yT94W" crossorigin="anonymous">

  <style>
    :root{ --page-width:210mm; --page-height:297mm; }
    body{ background: #f0f0f0; padding: 20px; }

    /* A4 container */
    .invoice { width: var(--page-width); min-height: var(--page-height); margin: 0 auto 20px; background: white; box-shadow: 0 0 0.5cm rgba(0,0,0,0.15); padding: 16mm; box-sizing: border-box; color: #222; font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial; }

    header, footer { width: 100%; }

    /* Table style */
    .items-table th, .items-table td{ vertical-align: middle; }

    .table thead th { border-bottom: 2px solid #dee2e6; }

    /* Print settings */
    @page { size: A4; margin: 0; }
    @media print { body { background: none; padding: 0; } .invoice { box-shadow: none; margin: 0; padding: 10mm; } .no-print { display: none !important; } }

    /* Small helpers */
    .right { text-align: right; }
    .muted { color: #6c757d; }
  </style>
</head>
<body>

  <div class="invoice" id="invoice">

    <!-- Header (will be loaded from external source) -->
    <header id="invoice-header" class="mb-3">
      <?php replaceVars($rss["n7"]);?>
    </header>

    <!-- Main -->
    <main>
      <!-- Alıcı bilgileri / kısa özet bölümü -->
      <section class="mb-4" style="margin-bottom:15px;">
        <div class="row">
          <div class="col-8">
            <strong>Alıcı:</strong>
            <div id="buyer-info">[Alıcı Firma / Kişi Bilgileri]</div>
          </div>
          
        </div>
      </section>

      <section style="margin-bottom:15px;">
        <div class="table-responsive">
          <table class="table table-sm table-bordered items-table">
            <thead class="table-light">
              <tr>
                <th style="width:12%">Ürün Kodu</th>
                <th style="width:38%">Ürün Adı</th>
                <th style="width:8%" class="text-end">Adet</th>
                <th style="width:15%" class="text-end">Birim Fiyat</th>
                <th style="width:15%" class="text-end">Toplam</th>
              </tr>
            </thead>
            <tbody id="items-body">
              <!-- örnek satır -->
              <?php
            include("../accounting/accounting_calc.php");
            $sqlfu=mysqli_query($conn, "select * from t4 where ne='furun' and s1=".$_GET["id"]." order by id desc"); while($rsfu=mysqli_fetch_assoc($sqlfu)){
            $sqlu=mysqli_query($conn, "select * from ".$_SESSION["lang"]." where id=".$rsfu["s2"].""); $rsu=mysqli_fetch_assoc($sqlu);
			$sqlv=mysqli_query($conn, "select * from genel where id=".$rsfu["s6"].""); $rsv=mysqli_fetch_assoc($sqlv);
			$jsi = json_decode($rsfu["n17"], true);
            if(mysqli_num_rows($sqlu)>0){
				$id=$rsu["id"]; include("../../../deppo/tools/script/prices.php");
				$uAdi=$rsu["t1"];
				$uKod=$rsu["t4"];
			}else{
				$uAdi=$rsfu["n1"];
				$uKod="U0000000";
			}
            ?>
              <!----------------------------------------------/uSatır/--->
              <tr>
               <td><?php echo $uKod?><?php if($rsu["t5"]<>""){echo "<br>".$rsu["t5"];}?></td>
               <td><?php echo $uAdi?><?php if(mysqli_num_rows($sqlv)>0){echo " {".$rsv["t1"]."}";}?>
					<?php $sqli=mysqli_query($conn, "select * from genel where ne='inputs' and (t2='All' or t2='".$_SESSION["lang"]."') and n3='kayit' and n4<>'switch' and (n2='0' or n2='".$rsu["id"]."') and n6='required' and s1=0 order by s10,id asc");?>
					<?php if(mysqli_num_rows($sqli)>0){?>
					<div style="font-size:12px;">
					<?php $i=0; while($rsi=mysqli_fetch_assoc($sqli)){$i++;?>
						<?php if($rsi["n4"]=="input" or $rsi["n4"]=="textarea"){?>
						<?php if($jsi["i".$i.""]<>""){?>	<b><?php echo $rsi["n1"];?></b> : <?php echo $jsi["i".$i.""];?><?php }?>
						<?php }else{?>
						<?php if($jsi["i".$i.""][0]<>""){?>	<b><?php echo $rsi["n1"];?></b> : <?php echo $jsi["i".$i.""][0];?><?php }?>
						<?php }?>
					<?php }?>
					</div>
					<?php }?>
			   </td>
               <td><?php echo $rsfu["s5"]?> <?php echo $rsfu["t10"];?></td>
               <td style="text-align:right;"><?php echo wprice($rsfu["pb1"])?>&nbsp;<i class="fa fa-<?php echo strtolower($rsfu["t10"]);?>"></i></td>
               <td style="text-align:right;"><?php echo wprice($rsfu["pb1"]*$rsfu["s5"])?></td>
           </tr>
       <?php }?>
            </tbody>
          </table>
        </div>
        <!-- Alt toplam / KDV / Genel toplam -->
        <div class="row mt-3">
          <div class="col-6">

          </div>
          <div class="col-6">
            <ul style="list-style-type: none;">
			   <li style="text-align:right;"><span><?php echo translate("+Ara Toplam")?></span> : <?php echo wprice(($stotal))?> <?php echo $ikpb?></li>
			   <?php if (($stotal - $total) > 0): ?>
					<li style="text-align:right;"><span><?php echo translate("+İndirim")?></span> : <?php echo wprice($stotal - $total)?> <?php echo $ikpb?></li>
					<li style="text-align:right;"><span><?php echo translate("+Toplam")?></span> : <?php echo wprice(($total))?> <?php echo $ikpb?></li>
				<?php endif; ?>
			   <?php if(!empty($kdvbir)){?><li style="text-align:right;"><span><?php echo $sdil[86]; //Tax?> 1%</span> : <?php echo wprice(($kdvbir))?> <?php echo $ikpb?></li><?php }?>
			   <?php if(!empty($kdvsekiz)){?><li style="text-align:right;"><span><?php echo $sdil[86]; //Tax?> 8%</span> : <?php echo wprice(($kdvsekiz))?> <?php echo $ikpb?></li><?php }?>
			   <?php if(!empty($kdvonsekiz)){?><li style="text-align:right;"><span><?php echo $sdil[86]; //Tax?> 18%</span> : <?php echo wprice(($kdvonsekiz))?> <?php echo $ikpb?></li><?php }?>
			   <?php if(!empty($kdvdiger)){?><li style="text-align:right;"><span><?php echo $sdil[86]; //Tax?> </span> : <?php echo wprice(($kdvdiger))?> <i class="fa fa-<?php echo strtolower($kpb)?>"></i></li><?php }?>
			   <li style="text-align:right;"><span><?php echo translate("+Genel Toplam")?></span> : <?php echo wprice(($gtotal))?> <?php echo $ikpb?></li>
		   </ul>
          </div>
        </div>
      </section>

    </main>

    <!-- Footer (will be loaded from external source) -->
    <footer id="invoice-footer" class="mt-4">
      <?php echo $rss["n6"]?>
    </footer>

  </div>

  <!-- Controls (no-print) -->
  <div class="container no-print mb-4">
    <div class="d-flex gap-2">
      <button id="printBtn" class="btn btn-primary">Yazdır / PDF</button>
    </div>
  </div>

  <!-- Bootstrap JS + Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-qQ2f8Y6FQ3Q5hZ6q9Gq2Q8J3Yj5s7k2jDq9Gq1k5h7L0p9f3" crossorigin="anonymous"></script>

  <script>
    // Varsayılan tarih
    document.getElementById('invoice-date').textContent = new Date().toLocaleDateString('tr-TR');

    // Basit örnek: header ve footer'u harici dosyalardan fetch ile yükleme
    // Kullanmak için butona basın veya sayfa yüklemesinde otomatik çağırın.
    async function loadHeaderFooter(headerUrl = '/header.html', footerUrl = '/footer.html'){
      try{
        const headerRes = await fetch(headerUrl);
        if(headerRes.ok){
          document.getElementById('invoice-header').innerHTML = await headerRes.text();
        }
      }catch(e){ /* sessiz hataları yoksay */ }

      try{
        const footerRes = await fetch(footerUrl);
        if(footerRes.ok){
          document.getElementById('invoice-footer').innerHTML = await footerRes.text();
        }
      }catch(e){ /* sessiz hataları yoksay */ }
    }

    // Buton davranışları
    document.getElementById('printBtn').addEventListener('click', function(){ window.print(); });
    document.getElementById('loadHeaderFooter').addEventListener('click', function(){
      // isterseniz parametreli çağrı: loadHeaderFooter('/partials/header-proforma.html','/partials/footer-proforma.html')
      loadHeaderFooter();
    });

    // Eğer header/footer URL'lerini sayfa içinde data attribute ile vermek isterseniz:
    // örn: <div id="invoice" data-header="/h.html" data-footer="/f.html"></div>
    (function(){
      const inv = document.getElementById('invoice');
      const h = inv.getAttribute('data-header');
      const f = inv.getAttribute('data-footer');
      if(h || f) loadHeaderFooter(h || undefined, f || undefined);
    })();
  </script>

</body>
</html>