<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['sales_manager', 'sales_executive'])) {
    echo "Access Denied";
    exit;
}

require_once '../config.php';

function e($v) {
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}

function money($n) {
    return number_format((float)$n, 2, '.', ',');
}

$bill_id = (int)($_GET['id'] ?? 0);
if ($bill_id <= 0) {
    die("Invalid Bill ID");
}

$stmt = $conn->prepare("SELECT * FROM bills WHERE id = ?");
$stmt->bind_param("i", $bill_id);
$stmt->execute();
$bill = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$bill) {
    die("Bill not found");
}

$stmt = $conn->prepare("SELECT * FROM bill_items WHERE bill_id = ? ORDER BY id ASC");
$stmt->bind_param("i", $bill_id);
$stmt->execute();
$items = $stmt->get_result();
$stmt->close();

$total = 0.0;
$itemRows = [];

while ($item = $items->fetch_assoc()) {
    $qty = (float)($item['qty'] ?? 0);
    $price = (float)($item['price'] ?? 0);
    $rowTotal = isset($item['total']) && $item['total'] !== '' ? (float)$item['total'] : ($qty * $price);

 $itemRows[] = [
    'product_name' => $item['product_name'] ?? '-',
    'qty'          => $qty,
    'price'        => $price,
    'total'        => $rowTotal,
    'discount'     => (float)($item['discount'] ?? 0),
    'sgst'         => (float)($item['sgst'] ?? 0),
    'cgst'         => (float)($item['cgst'] ?? 0),
];

   
}

$billDate = !empty($bill['created_at']) ? date('d-m-Y', strtotime($bill['created_at'])) : date('d-m-Y');
$status   = trim((string)($bill['payment_status'] ?? 'Paid'));

$companyName = $bill['company_name'] ?? 'Bionick';
$companyAddr  = $bill['company_address'] ?? 'Bopal, Ahmedabad';
$companyGST   = $bill['company_gst'] ?? '335AGSHS778';
$companyPhone = $bill['company_phone'] ?? '7645585689';

$logoPath = '';
foreach ([
    __DIR__ . '/uploads/logo.png',
    __DIR__ . '/assets/img/logo.png',
    __DIR__ . '/assets/image/logo.png',
    __DIR__ . '/logo.png'
] as $p) {
    if (file_exists($p)) {
        $logoPath = $p;
        break;
    }
}

function embed_image($path) {
    if (!$path || !file_exists($path)) return '';
    $raw = @file_get_contents($path);
    if ($raw === false) return '';
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    $mime = 'image/png';
    if (in_array($ext, ['jpg', 'jpeg'])) $mime = 'image/jpeg';
    elseif ($ext === 'gif') $mime = 'image/gif';
    return 'data:' . $mime . ';base64,' . base64_encode($raw);
}

$logoSrc = $logoPath ? embed_image($logoPath) : '';

$terms = [];
$table_check = $conn->query("SHOW TABLES LIKE 'terms_conditions'");
if ($table_check && $table_check->num_rows > 0 && !empty($_SESSION['email'])) {
    $terms_stmt = $conn->prepare("SELECT term_text FROM terms_conditions WHERE admin_email = ? ORDER BY id ASC");
    if ($terms_stmt) {
        $terms_stmt->bind_param("s", $_SESSION['email']);
        if ($terms_stmt->execute()) {
            $res = $terms_stmt->get_result();
            while ($row = $res->fetch_assoc()) {
                $txt = trim((string)($row['term_text'] ?? ''));
                if ($txt !== '') $terms[] = $txt;
            }
        }
        $terms_stmt->close();
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Invoice #<?php echo e($bill['id']); ?></title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

<style>
  :root{
    --bg:#f3f6fb;
    --card:#ffffff;
    --border:#e6ebf2;
    --text:#0f172a;
    --muted:#64748b;
    --heading:#24364b;
    --dark:#2f3e52;
    --green-bg:#dcfce7;
    --green-text:#166534;
    --green-border:#86efac;
  }

  * { box-sizing: border-box; }

  body{
    margin:0;
    font-family: Arial, Helvetica, sans-serif;
    background: var(--bg);
    color: var(--text);
  }

  .toolbar{
    max-width: 980px;
    margin: 18px auto 0;
    display:flex;
    justify-content:flex-end;
    gap:10px;
    padding:0 12px;
  }

  .btn{
    border:none;
    border-radius:8px;
    padding:10px 16px;
    font-weight:700;
    cursor:pointer;
    font-size:14px;
  }

  .btn-back{ background:#6b7280; color:#fff; }
  .btn-print{ background:#111827; color:#fff; }
  .btn-pdf{ background:#dc2626; color:#fff; }

  .invoice{
    max-width: 980px;
    margin: 14px auto 40px;
    background: var(--card);
    border:1px solid #dfe7ef;
    border-radius:14px;
    box-shadow:0 8px 26px rgba(15,23,42,.06);
    padding:24px 28px;
  }

  .top-logo{
    display:flex;
    align-items:flex-start;
    justify-content:flex-start;
    padding-bottom:14px;
    border-bottom:1px solid #edf2f7;
    margin-bottom:16px;
    min-height:78px;
  }

  .top-logo img{
    max-width:130px;
    max-height:60px;
    object-fit:contain;
  }

  .header-row{
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
    gap:16px;
    margin-bottom:18px;
  }

  .left-block{ width:40%; }
  .center-block{
    width:18%;
    display:flex;
    justify-content:center;
    align-items:center;
    min-height:72px;
  }
  .right-block{ width:42%; text-align:right; }

  .company-name{
    font-family: Georgia, 'Times New Roman', serif;
    font-size:24px;
    font-weight:700;
    color:#1f3a5f;
    margin:0 0 8px;
  }

  .small-text{
    font-size:13px;
    color:var(--muted);
    line-height:1.45;
  }

  .invoice-title{
    font-size:24px;
    font-weight:800;
    color:#1f2937;
    margin:0 0 10px;
    letter-spacing:.2px;
  }

  .badge-paid{
    display:inline-block;
    background:var(--green-bg);
    color:var(--green-text);
    border:1px solid var(--green-border);
    border-radius:999px;
    padding:10px 22px;
    font-weight:800;
    font-size:16px;
    min-width:110px;
    text-align:center;
    text-transform:capitalize;
  }

  .items-title{
    font-size:17px;
    font-weight:800;
    margin:14px 0 10px;
    color:var(--heading);
  }

  .table-wrap{
    overflow:hidden;
    border-radius:10px;
    border:1px solid #edf2f7;
  }

  table.items{
    width:100%;
    border-collapse:collapse;
    table-layout:fixed;
    font-size:12px;
  }

  table.items thead th{
    background:#2f3e52;
    color:#fff;
    padding:10px 8px;
    text-align:left;
    white-space:nowrap;
  }

  table.items td{
    padding:10px 8px;
    border-bottom:1px solid #edf2f7;
    vertical-align:middle;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }

  .c-sno{ width:6%; text-align:center; }
  .c-prod{ width:46%; }
  .c-qty{ width:10%; text-align:center; }
  .c-rate{ width:19%; text-align:right; }
  .c-total{ width:19%; text-align:right; font-weight:700; }

  .summary{
    width: 360px;
    margin-left:auto;
    margin-top:18px;
    border-top:1px solid #edf2f7;
  }

  .summary table{
    width:100%;
    border-collapse:collapse;
    margin-top:12px;
  }

  .summary td{
    padding:10px 12px;
    border-bottom:1px solid #edf2f7;
    font-size:13px;
  }

  .summary td.label{
    font-weight:700;
    color:#334155;
  }

  .summary td.value{
    text-align:right;
  }

  .summary tr.grand td{
    font-weight:800;
    font-size:15px;
    color:#111827;
  }

  .note{
    text-align:center;
    color:var(--muted);
    font-size:12px;
    margin:18px 0 12px;
  }

  .terms-section{
    margin-top:10px;
    border-top:1px solid #e5e7eb;
    padding-top:12px;
    page-break-inside:avoid;
  }

  .terms-title{
    font-size:16px;
    font-weight:800;
    color:var(--heading);
    margin:0 0 8px;
  }

  .terms-section ol{
    margin:0;
    padding-left:18px;
    color:#334155;
    font-size:12px;
    line-height:1.55;
  }

  .no-print { display:block; }

  @media print{
    .toolbar{ display:none !important; }
    body{ background:#fff; }
    .invoice{
      margin:0;
      box-shadow:none;
      border:none;
      border-radius:0;
    }
  }

  @page{
    size:A4;
    margin:10mm;
  }
</style>
</head>
<body>

<div class="toolbar no-print">
  <a href="sold_products.php" class="btn btn-back">Back</a>
  <button class="btn btn-print" onclick="window.print()">Print Invoice</button>
  <button class="btn btn-pdf" onclick="downloadPDF()">Download PDF</button>
</div>

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

  <div class="top-logo">
    <?php if ($logoSrc): ?>
      <img src="<?php echo e($logoSrc); ?>" alt="Logo">
    <?php endif; ?>
  </div>

  <div class="header-row">
    <div class="left-block">
      <div class="company-name"><?php echo e($companyName); ?></div>
      <div class="small-text">
        <?php echo nl2br(e($companyAddr)); ?><br>
        GST NO: <?php echo e($companyGST); ?><br>
        Phone: <?php echo e($companyPhone); ?>
      </div>
    </div>

    <div class="center-block">
      <span class="badge-paid"><?php echo e($status); ?></span>
    </div>

    <div class="right-block">
      <div class="invoice-title">INVOICE</div>
      <div class="small-text" style="font-weight:700;color:#334155;">
        Bill No: <?php echo e($bill['bill_no'] ?? $bill['id']); ?><br>
        Date: <?php echo e($billDate); ?><br>
        Customer: <?php echo e($bill['customer_name'] ?? '-'); ?><br>
        Phone: <?php echo e($bill['phone'] ?? '-'); ?>
      </div>
    </div>
  </div>

  <div class="items-title">Items</div>

  <div class="table-wrap">
    <table class="items">
      <thead>
  <tr>
    <th>S.No</th>
    <th>Product</th>
    <th>Unit</th>
    <th>Qty</th>
    <th>Price</th>
    <th>Discount</th>
    <th>SGST</th>
    <th>CGST</th>
    <th>Total</th>
  </tr>
</thead>
      <tbody>
<?php 
$i = 1;

$subtotal = 0;
$discount_total = 0;
$sgst_total = 0;
$cgst_total = 0;
$total = 0;

foreach ($itemRows as $item):

$qty = (float)$item['qty'];
$price = (float)$item['price'];
$line_total = (float)$item['total'];

$discount = (float)($item['discount'] ?? 0);
$sgst = (float)($item['sgst'] ?? 0);
$cgst = (float)($item['cgst'] ?? 0);

$unit = ($qty > 0) ? ($line_total / $qty) : $price;

$taxable = $line_total - $discount;
$final = $taxable + $sgst + $cgst;

$subtotal += $line_total;
$discount_total += $discount;
$sgst_total += $sgst;
$cgst_total += $cgst;
$total += $final;
?>
<tr>
  <td class="c-sno"><?php echo $i++; ?></td>

  <td class="c-prod"><?php echo e($item['product_name']); ?></td>

  <td class="c-rate"><?php echo money($unit); ?></td>

  <td class="c-qty"><?php echo $qty; ?></td>

  <td class="c-rate"><?php echo money($line_total); ?></td>

  <td class="c-rate"><?php echo money($discount); ?></td>

  <td class="c-rate"><?php echo money($sgst); ?></td>

  <td class="c-rate"><?php echo money($cgst); ?></td>

  <td class="c-total"><?php echo money($final); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
    </table>
  </div>

  <div class="summary">
   <table>
  <tr>
    <td class="label">Subtotal</td>
    <td class="value"><?php echo money($subtotal); ?></td>
  </tr>
  <tr>
    <td class="label">Discount</td>
    <td class="value" style="color:#16a34a;"><?php echo money($discount_total); ?></td>
  </tr>
  <tr>
    <td class="label">Taxable Amount</td>
    <td class="value"><?php echo money($subtotal - $discount_total); ?></td>
  </tr>
  <tr>
    <td class="label">Total SGST</td>
    <td class="value"><?php echo money($sgst_total); ?></td>
  </tr>
  <tr>
    <td class="label">Total CGST</td>
    <td class="value"><?php echo money($cgst_total); ?></td>
  </tr>
  <tr class="grand">
    <td class="label">Grand Total</td>
    <td class="value"><?php echo money($total); ?></td>
  </tr>
</table>
  </div>

  <div class="note">
    Thank you for your purchase! This is a system generated invoice.
  </div>

  <?php if (!empty($terms)): ?>
    <div class="terms-section">
      <div class="terms-title">Terms &amp; Conditions</div>
      <ol>
        <?php foreach ($terms as $t): ?>
          <li><?php echo e($t); ?></li>
        <?php endforeach; ?>
      </ol>
    </div>
  <?php endif; ?>

</div>

<script>
function downloadPDF() {
  const element = document.getElementById('invoice');
  const toolbar = document.querySelector('.toolbar');

  // Hide buttons before generating PDF
  if (toolbar) toolbar.style.display = 'none';

  const opt = {
    margin: 0.15,
    filename: 'Invoice_<?php echo e($bill['bill_no'] ?? $bill['id']); ?>.pdf',
    image: { type: 'jpeg', quality: 1 },
    html2canvas: { scale: 3, useCORS: true, scrollY: 0 },
    jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' }
  };

  html2pdf().set(opt).from(element).save().then(() => {
    // Show buttons again after PDF
    if (toolbar) toolbar.style.display = 'flex';
  });
}
</script>

</body>
</html>