<?php
include('../db/cn.php');
ob_start();

$orderId = $_GET["order_id"];


$t = mysqli_query($connection,"SELECT *  FROM log_user_sales 
                               WHERE order_id = '$orderId' ");
$r = mysqli_fetch_assoc($t);

$tt = mysqli_query($connection,"SELECT * FROM log_user_sales 
                               WHERE order_id = '$orderId'");

$trr = mysqli_fetch_array($tt);

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Invoice - Fine & Fair</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {
      font-family: Arial, sans-serif;
      font-size: 14px;
    }
    .invoice-box {
      padding: 20px;
      max-width: 1000px;
      margin: auto;
      border: 1px solid #eee;
      background: #fff;
    }
    .fw-600 { font-weight: 600; }
    .table th, .table td { vertical-align: middle; }
    @media print {
  .no-print { display: none; }
}
  </style>
</head>
<body>
<div class="invoice-box">
  <div class="text-center mb-3">
    <h3 class="fw-bold">Fine & Fair</h3>
    <div>Einzel und Großhandel<br>Indisches Lebensmittel Geschäft<br>Balinger Str. 1, 70567, Stuttgart<br>Mobile: 015215481967 Ph. 0711 69988947</div>
  </div>
<div style="border:1px solid #000; display:flex; font-size:12px; max-width:750px; margin:auto;">
  <!-- Left side -->
  <div style="flex:1; border-right:1px solid #000; padding:8px;">
    <div style="display: flex; justify-content: space-between;">
        <p>
            Rechnung Nr.: <strong><?php echo htmlspecialchars($orderId); ?></strong><br>
            Datum: <strong><?php echo date("d-m-Y", strtotime($r["date_time"])); ?></strong>
        </p>
    </div>
    <p>Liefer Datum: <strong><?php echo $r['d_date']; ?></strong><br>
    Lieferschein Nr.: <strong><?php echo htmlspecialchars($orderId); ?></strong></p>
    
    <?php
      $cutomer = $trr['customer_name'];
      $cus = mysqli_query($connection,"select * from credit_note where cr_name = '$cutomer'");
      $re = mysqli_fetch_array($cus);
    ?>
    <br>
  
    <p>
      <strong>Kunde.Nr</strong> <?php echo $re['cr_id']; ?><br>
      <strong style="font-weight:700;"><?php echo $re["cr_name"]; ?></strong><br>
      <?php echo $re["phone_number"]; ?><br>
      <?php echo $re['cr_address']; ?><br>
      <?php echo $re['city']; ?><br>
      <?php echo $re['p_code']; ?>
    </p>
  </div>

  <!-- Right side -->
  <div style="flex:1; padding:8px;">
    <p>VAT Nr.: <strong>DE359845492</strong></p>
    <br><br><br><br><br>
    <strong>Bank Details:</strong>
    <p>
      Name des Begünstigten: <strong>Saima Jabeen</strong><br>
      Name der Bank: <strong>BW-Bank</strong><br>
      BIC (SWIFT): <strong>SOLADEST</strong><br>
      IBAN: <strong>DE52 6005 0101 0405 6456 51</strong>
    </p>
  </div>
</div>

<br>
  <table class="table table-bordered text-center align-middle table-sm" 
       style="font-size:12px; max-width:750px; margin:auto; ">
  <thead style="background:#f9f9f9;">
    <tr>
      <th style="padding:4px;">POS</th>
      <th style="padding:4px;">Nr.</th>
      <th style="padding:4px;">ARTIKEL</th>
      <th style="padding:4px;">MENGE</th>
      <th style="padding:4px;">EINZEL<br>PREIS EUR</th>
      <th style="padding:4px;">MwSt.<br>%</th>
      <th style="padding:4px;">GESAMT<br>EUR</th>
    </tr>
  </thead>
  <tbody>
   <?php
     $sr = 1;
     $p = mysqli_query($connection,"select * from log_user_sales where order_id = '$orderId'");
     while($row = mysqli_fetch_array($p)){
   ?>
   <tr>
     <td style="padding:4px;"><?php  echo $sr++ ;?></td>
     <td style="padding:4px;"><?php  echo $row["product_id"];?></td>
     <td style="padding:4px; text-align:left;"><?php  echo $row["product_name"] ;?></td> 
     <td style="padding:4px;"><?php  echo $row["product_quantity"] ;?></td> 
     <td style="padding:4px;"><?php  echo $row["product_price"] ;?></td>
     <td style="padding:4px;"><?php  echo $row["wh_percentage"].'%' ;?></td>
     <td style="padding:4px;"><?php  echo $row["product_total"] ;?></td>
   </tr>
   <?php
     }
   ?>
  </tbody>
  <?php 
    $s7 = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$orderId' AND wh_percentage = '7'");
    $total7 = 0;
    while ($r7 = mysqli_fetch_array($s7)) {
        $total7 += $r7["net_amount"];
    }
    $tax7 = $total7 * 0.07;
    $net7 = $total7 - $tax7;

    $s19 = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$orderId' AND wh_percentage = '19'");
    $total19 = 0;
    while ($r19 = mysqli_fetch_array($s19)) {
        $total19 += $r19["net_amount"];
    }
    $tax19 = $total19 * 0.19;
    $net19 = $total19 - $tax19;
  ?>
  <tfoot>
    <tr>
      <td colspan="6" class="text-end" style="padding:4px;"><strong>Gesamt Netto</strong></td>
      <td style="padding:4px;"><strong><?php  echo $r["grand_amount"];?></strong></td>
    </tr>
    <tr>
      <td colspan="6" class="text-end" style="padding:4px;">MwSt. 7%</td>
      <td style="padding:4px;"><?php  echo $tax7;?></td>
    </tr>
    <tr>
      <td colspan="6" class="text-end" style="padding:4px;">MwSt. 19%</td>
      <td style="padding:4px;"><?php  echo $tax19 ;?></td>
    </tr>
    <tr>
      <td colspan="6" class="text-end fw-bold" style="padding:4px;">Rechnungsbetrag.. (TOTAL AMOUNT)</td>
      <td class="fw-bold" style="padding:4px;"><?php  echo $r["grand_amount"];
      $discountAmountss = $r['grand_amount'];
      ;?></td>
    </tr>
  </tfoot>
</table>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['exit'])) {
    if (!empty($cutomer) && $discountAmountss) {
        $checkQuery = "SELECT 1 FROM creditor_closing WHERE creditor_name = '$cutomer' LIMIT 1";
        $checkResult = mysqli_query($connection, $checkQuery);

        if (mysqli_num_rows($checkResult) > 0) {
            // Record exists: update
            $updateQuery = "UPDATE creditor_closing SET remain_balance = $discountAmountss WHERE creditor_name = '$cutomer'";
            $updateResult = mysqli_query($connection, $updateQuery);

            if ($updateResult) {
              echo "<script type='text/javascript'>window.location.href = 'mainpos.php';</script>";
                exit;
            } else {
                echo "<p style='color:red;'>Update failed: " . mysqli_error($connection) . "</p>";
            }
        } else {
            // Record doesn't exist: insert
            $insertQuery = "INSERT INTO creditor_closing (
                creditor_name, opening_cash, credit_sales, credit_recieved,
                remain_balance, date_time, login_user, user_role,
                outlet_name, outlet_address
            ) VALUES (
                '$cutomer', 0, 0, 0, $discountAmountss, NOW(), '$userName', '$useRole', '$outlet_name', '$outlet_address'
            )";

            $insertResult = mysqli_query($connection, $insertQuery);

            if ($insertResult) {
               echo "<script type='text/javascript'>window.location.href = 'mainpos.php';</script>";
                exit;
            } else {
                echo "<p style='color:red;'>Insert failed: " . mysqli_error($connection) . "</p>";
            }
        }
    }
}
?>
  
  <br><br>
  <center>
<div class="d-flex justify-content-center gap-2">
    <button class="no-print btn btn-primary" onclick="window.print()">Print</button>
  <a href="delivery_c.php?order_id=<?php echo $orderId; ?>" class="btn btn-dark no-print">Print Challan</a>
  <form method="post" style="display:inline;">
       <button type="submit" name="exit"  class=" btn btn-dark no-print">Exit</button>
       </form>
</div>
  </center>
</div>
</body>
</html>
