<?php
ob_start();
session_start();

include_once("../config.php");
include_once("../functions.php");

if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  exit();
}

include_once(ROOT_PATH . 'partial/report_top_common.php');
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_unit_status_info.php');
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_common.php');

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

/* -------- Inputs -------- */
$mode     = isset($_GET['mode']) ? trim($_GET['mode']) : '';
$block_id = isset($_GET['bid'])  ? (int)$_GET['bid']   : 0;
$unit_id  = isset($_GET['uid'])  ? (int)$_GET['uid']   : 0;

$is_all = (strtolower($mode) === 'all');

/* -------- Context: title bits -------- */
$context_title = 'All Units';
$unit_info     = ['unit_no' => '', 'b_name' => ''];

if (!$is_all) {
  if ($block_id <= 0 || $unit_id <= 0) {
    die("Invalid Block or Unit ID. Please go back and select a valid Block and Unit.");
  }
  // Fetch unit info for single-unit report
  if ($stmt = $link->prepare("SELECT unit_no, b_name FROM unit_view WHERE uid = ? LIMIT 1")) {
    $stmt->bind_param('i', $unit_id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res && $res->num_rows) {
      $unit_info = $res->fetch_assoc();
      $context_title = $unit_info['b_name'].' • '.$unit_info['unit_no'];
    }
    $stmt->close();
  }
} else {
  // Optional: if a block is provided + mode=all, narrow to that block for convenience
  if ($block_id > 0) {
    // Validate block name for header (optional)
    if ($stmt = $link->prepare("SELECT b_name FROM blocks WHERE bid = ? LIMIT 1")) {
      $stmt->bind_param('i', $block_id);
      $stmt->execute();
      $res = $stmt->get_result();
      if ($res && $res->num_rows) {
        $brow = $res->fetch_assoc();
        $context_title = $brow['b_name'].' • All Units';
      }
      $stmt->close();
    }
  }
}

/* -------- Fetch inventory rows -------- */
$items = [];
$total_qty = 0;
$item_count = 0;

if ($is_all) {
  // All units, optionally filter by block id
  if ($block_id > 0) {
    $sql = "
      SELECT u.b_name, u.unit_no, ui.item_name, ui.item_quantity, ui.inventory_added_date
      FROM units_inventory_view ui
      INNER JOIN unit_view u ON ui.unit_id = u.uid
      WHERE u.bid = ?
      ORDER BY u.b_name ASC, u.unit_no ASC, ui.item_name ASC
    ";
    if ($stmt = $link->prepare($sql)) {
      $stmt->bind_param('i', $block_id);
      $stmt->execute();
      $res = $stmt->get_result();
      while ($row = $res->fetch_assoc()) {
        $row['item_quantity'] = (int)$row['item_quantity'];
        $items[] = $row;
        $total_qty += $row['item_quantity'];
      }
      $stmt->close();
    }
  } else {
    $sql = "
      SELECT u.b_name, u.unit_no, ui.item_name, ui.item_quantity, ui.inventory_added_date
      FROM units_inventory_view ui
      INNER JOIN unit_view u ON ui.unit_id = u.uid
      ORDER BY u.b_name ASC, u.unit_no ASC, ui.item_name ASC
    ";
    if ($stmt = $link->prepare($sql)) {
      $stmt->execute();
      $res = $stmt->get_result();
      while ($row = $res->fetch_assoc()) {
        $row['item_quantity'] = (int)$row['item_quantity'];
        $items[] = $row;
        $total_qty += $row['item_quantity'];
      }
      $stmt->close();
    }
  }
  $item_count = count($items);

} else {
  // Single unit
  if ($stmt = $link->prepare("SELECT item_name, item_quantity, inventory_added_date FROM units_inventory_view WHERE unit_id = ? ORDER BY item_name ASC")) {
    $stmt->bind_param('i', $unit_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
      $row['item_quantity'] = (int)$row['item_quantity'];
      $items[] = $row;
      $total_qty += $row['item_quantity'];
    }
    $stmt->close();
  }
  $item_count = count($items);
}

?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Unit Inventory Report</title>
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <?php include_once(ROOT_PATH . '/partial/header_script.php'); ?>

  <!-- Font & Friendly Styles -->
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
  <style>
    :root{
      --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e2e8f0;
      --brand:#2563eb; --soft:#f8fafc; --soft2:#eef2ff; --ok:#16a34a;
    }
    body, .content-wrapper, .box, .table, .btn, .alert {
      font-family:'Inter', system-ui, Segoe UI, Roboto, Helvetica, Arial;
      color:var(--ink2);
      background:#f5f7fb;
    }
    .report-wrap{
      max-width: 1100px;
      margin: 24px auto 60px auto;
      padding: 0 12px;
    }
    .report-card{
      border:1px solid var(--line);
      background:#fff;
      border-radius:18px;
      overflow:hidden;
      box-shadow:0 12px 32px rgba(2,6,23,.06);
    }
    .report-header{
      padding:20px 24px;
      border-bottom:1px solid var(--line);
      background:linear-gradient(135deg,var(--soft),var(--soft2));
    }
    .report-title{
      margin:0;
      font-size:20px;
      font-weight:800;
      color:var(--ink);
      letter-spacing:.2px;
    }
    .report-meta{
      margin-top:6px;
      color:var(--muted);
      font-size:13px;
    }
    .report-body{
      padding:20px 24px;
    }
    .table{
      margin-bottom: 0;
      font-size:13px;
      background:#fff;
    }
    .table > thead > tr > th{
      font-weight:700; color:var(--ink); border-bottom:1px solid var(--line) !important;
      background:#fff;
    }
    .table > tbody > tr > td{
      vertical-align:middle;
    }
    tfoot td{
      font-weight:800;
      border-top:2px solid var(--line) !important;
      background:#fafafa;
    }
    .empty-row{
      text-align:center; color:var(--muted); font-style:italic;
    }
    .summary{
      display:flex; flex-wrap:wrap; gap:16px; margin-top:16px; color:var(--muted);
      font-size:13px; justify-content:flex-end;
    }
    .summary > div strong{ color:var(--ink2); }

    /* Signature card — larger area for writing names & signatures */
    .sig-card{
      margin-top:28px;
      border:1px dashed var(--line);
      border-radius:14px;
      overflow:hidden;
      background:#fff;
    }
    .sig-card table{
      margin:0;
      background:#fff;
      table-layout: fixed;
    }
    .sig-card th{
      text-align:center;
      background:#fafafa;
      font-weight:700;
      color:var(--ink2);
      padding:12px 10px;
      font-size:14px;
      border-bottom:1px solid var(--line);
    }
    .sig-cell{
      padding:24px 20px 18px;
      vertical-align:bottom;
    }
    .sig-pad{
      min-height: 260px;
      display:flex;
      flex-direction:column;
      justify-content:flex-end;
      gap:16px;
    }
    .sig-blank{
      flex:1 1 auto;
      border:1px dashed #e5e7eb;
      border-radius:8px;
      background:#fff;
    }
    .sig-line{
      width:100%;
      border-top:2px solid #cbd5e1;
      margin:0 0 2px 0;
    }
    .sig-caption{
      font-size:12px; color:var(--muted); text-align:left;
    }
    .sig-row{
      display:grid;
      grid-template-columns: 1fr 140px;
      gap:16px;
      align-items:end;
    }
    .sig-line.short{
      border-top:2px solid #cbd5e1;
      width:100%;
    }

    .print-fab{
      position:fixed; right:16px; top:12px; z-index:9999;
    }
    .btn{
      border-radius:10px;
    }
    .btn-success{ background:var(--ok); border-color:var(--ok); }
    .btn-success:hover{ background:#15803d; border-color:#15803d; }
    .badge{
      display:inline-block; padding:4px 10px; border-radius:999px;
      border:1px solid var(--line); font-size:12px; font-weight:600; color:var(--muted);
      background:#fff;
    }

    @media print {
      .print-fab { display:none !important; }
      body { background:#fff; }
      .report-card { box-shadow:none; border:1px solid #ddd; }
      .sig-blank { border-color:#d1d5db; }
    }
  </style>

  <script type="text/javascript">
    function printContent(area, title) {
      // Requires printThis loaded in header_script.php
      $("#" + area).printThis({ pageTitle: title });
    }
  </script>
</head>
<body>

<section class="content">
  <div class="report-wrap" id="printable">
    <input type="hidden" id="web_url" value="<?= WEB_URL; ?>" />

    <!-- Top Brand / Title Section from your common partial -->
    <?php include_once(ROOT_PATH . 'partial/report_top_title.php'); ?>

    <div class="report-card">
      <div class="report-header">
        <h3 class="report-title">
          Unit Inventory Report — <?= e($context_title); ?>
        </h3>
        <div class="report-meta">
          Printed on: <?= date('M d, Y \a\\t h:i A'); ?>
          <span class="badge" style="margin-left:10px;"><?= (int)$item_count; ?> item<?= $item_count === 1 ? '' : 's'; ?></span>
        </div>
      </div>

      <div class="report-body">
        <div class="table-responsive">
          <table class="table table-bordered table-striped dt-responsive">
            <thead>
              <tr>
                <?php if ($is_all): ?>
                  <th style="width:20%;">Block</th>
                  <th style="width:15%;">Unit</th>
                  <th style="width:40%;">Item Name</th>
                  <th style="width:10%;">Quantity</th>
                  <th style="width:15%;">Added Date</th>
                <?php else: ?>
                  <th style="width:55%;">Item Name</th>
                  <th style="width:20%;">Item Quantity</th>
                  <th style="width:25%;">Added Date</th>
                <?php endif; ?>
              </tr>
            </thead>
            <tbody>
              <?php if ($item_count > 0): ?>
                <?php foreach ($items as $row): ?>
                  <?php if ($is_all): ?>
                    <tr>
                      <td><?= e($row['b_name']); ?></td>
                      <td><?= e($row['unit_no']); ?></td>
                      <td><?= e($row['item_name']); ?></td>
                      <td><?= (int)$row['item_quantity']; ?></td>
                      <td><?= e($row['inventory_added_date']); ?></td>
                    </tr>
                  <?php else: ?>
                    <tr>
                      <td><?= e($row['item_name']); ?></td>
                      <td><?= (int)$row['item_quantity']; ?></td>
                      <td><?= e($row['inventory_added_date']); ?></td>
                    </tr>
                  <?php endif; ?>
                <?php endforeach; ?>
              <?php else: ?>
                <tr>
                  <td colspan="<?= $is_all ? 5 : 3; ?>" class="empty-row">No inventory items found<?= $is_all ? '' : ' for this unit'; ?>.</td>
                </tr>
              <?php endif; ?>
            </tbody>
            <tfoot>
              <tr>
                <?php if ($is_all): ?>
                  <td colspan="3" style="text-align:right;">Total Quantity</td>
                  <td><?= (int)$total_qty; ?></td>
                  <td></td>
                <?php else: ?>
                  <td style="text-align:right;">Total Quantity</td>
                  <td><?= (int)$total_qty; ?></td>
                  <td></td>
                <?php endif; ?>
              </tr>
            </tfoot>
          </table>
        </div>

        <div class="summary">
          <?php if ($is_all): ?>
            <?php if ($block_id > 0): ?>
              <div><strong>Block:</strong> <?= e($context_title); ?></div>
            <?php else: ?>
              <div><strong>Scope:</strong> All Blocks • All Units</div>
            <?php endif; ?>
          <?php else: ?>
            <div><strong>Block:</strong> <?= e($unit_info['b_name']); ?></div>
            <div><strong>Unit:</strong> <?= e($unit_info['unit_no']); ?></div>
          <?php endif; ?>
          <div><strong>Total Items:</strong> <?= (int)$item_count; ?></div>
          <div><strong>Total Quantity:</strong> <?= (int)$total_qty; ?></div>
        </div>

        <!-- Signature Block (expanded writing area) -->
        <div class="sig-card">
          <table class="table table-bordered">
            <tr>
              <th style="width: 50%;">Name and Signature of Caretaker</th>
              <th style="width: 50%;">Name and Signature of Guest</th>
            </tr>
            <tr>
              <td class="sig-cell">
                <div class="sig-pad">
                  <div class="sig-blank"></div>
                  <div>
                    <div class="sig-line"></div>
                    <div class="sig-caption">Signature</div>
                  </div>
                  <div>
                    <div class="sig-line"></div>
                    <div class="sig-caption">Name</div>
                  </div>
                  <div class="sig-row">
                    <div>
                      <div class="sig-line"></div>
                      <div class="sig-caption">Phone No.</div>
                    </div>
                    <div>
                      <div class="sig-line short"></div>
                      <div class="sig-caption">Date</div>
                    </div>
                  </div>
                </div>
              </td>
              <td class="sig-cell">
                <div class="sig-pad">
                  <div class="sig-blank"></div>
                  <div>
                    <div class="sig-line"></div>
                    <div class="sig-caption">Signature</div>
                  </div>
                  <div>
                    <div class="sig-line"></div>
                    <div class="sig-caption">Name</div>
                  </div>
                  <div class="sig-row">
                    <div>
                      <div class="sig-line"></div>
                      <div class="sig-caption">Phone No.</div>
                    </div>
                    <div>
                      <div class="sig-line short"></div>
                      <div class="sig-caption">Date</div>
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          </table>
        </div>

      </div>
    </div>
  </div>
</section>

<!-- Floating Print Button -->
<div class="print-fab">
  <a class="btn btn-success btn_save"
     title="Print Report"
     onclick="printContent('printable','Unit Inventory Report');"
     href="javascript:void(0);">
    <i class="fa fa-print"></i> Print
  </a>
</div>

</body>
</html>
