<?php
ob_start();
session_start();
include_once("../config.php");
include_once("../functions.php");
if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}

include_once(ROOT_PATH . 'partial/report_top_common.php');
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_fair_info_all.php');
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_common.php');
include_once(ROOT_PATH . 'library/helper.php');

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

/* ---------- Filters / Title Dates ---------- */
$get_data          = get_input_serilization();
$start_date_filter = !empty($get_data['startDate']) ? $get_data['startDate'] : '';
$end_date_filter   = !empty($get_data['endDate'])   ? $get_data['endDate']   : '';
$date_range_title  = (!empty($start_date_filter) && !empty($end_date_filter))
  ? " (" . date("jS F, Y", strtotime($start_date_filter)) . " - " . date("jS F, Y", strtotime($end_date_filter)) . ")"
  : "";

/* ---------- Build Query (JOIN to unit_view for names) ---------- */
$sql = "
  SELECT
    m.*,
    COALESCE(uv.b_name, b.b_name) AS b_name,
    uv.unit_no
  FROM maintenance AS m
  LEFT JOIN unit_view   AS uv ON uv.uid = m.uid
  LEFT JOIN blocks   AS b  ON b.bid = m.bid
  WHERE 1
";
if (!empty($get_data['bid']))      { $bid = (int)$get_data['bid'];  $sql .= " AND m.bid = {$bid}"; }
if (!empty($get_data['uid']))      { $uid = (int)$get_data['uid'];  $sql .= " AND m.uid = {$uid}"; }
if (!empty($get_data['startDate'])){ $sd  = $get_data['startDate']; $sql .= " AND m.m_date >= '{$sd}'"; }
if (!empty($get_data['endDate']))  { $ed  = $get_data['endDate'];   $sql .= " AND m.m_date <= ('{$ed}' + INTERVAL 1 DAY)"; }
$sql .= " ORDER BY m.m_date DESC";

$result     = $link->query($sql);
$total_cost = 0;
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title><?= e($building_name); ?> — Maintenance 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'); ?>

  <script type="text/javascript">
    function printContent(area, title){
      $("#" + area).printThis({ pageTitle: title });
    }
  </script>

  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;800&display=swap" rel="stylesheet">
  <style>
    :root{
      --page:#f5f7fb;
      --card:#ffffff;
      --ink:#0f172a;
      --ink-2:#334155;
      --muted:#64748b;
      --line:#e5e7eb;
      --soft:#f9fafb;
      --soft2:#eef2ff;
      --brand:#2563eb;
      --ok:#16a34a;
      --warn:#d97706;
      --danger:#dc2626;
    }
    html, body{
      background:var(--page);
      color:var(--ink-2);
      font-family:'Inter',system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial;
      -webkit-font-smoothing:antialiased;
      -moz-osx-font-smoothing:grayscale;
    }

    /* Container spacing similar to AdminLTE content */
    section.content{ padding: 15px; }

    /* Card */
    .box.box-success{
      background:var(--card);
      border:1px solid var(--line);
      border-radius:16px;
      overflow:hidden;
      box-shadow:0 14px 36px rgba(2,6,23,.08);
    }
    .box .box-header{
      background:linear-gradient(135deg,var(--soft),var(--soft2));
      border-bottom:1px solid var(--line);
      padding:14px 16px;
      display:flex; align-items:center; justify-content:space-between; gap:12px;
    }
    .box .box-title{
      margin:0; font-weight:800; color:var(--ink); letter-spacing:.2px;
      display:flex; align-items:center; gap:8px;
    }
    .box .box-body{ padding:16px; background:var(--card); }

    /* Chips (filter summary) */
    .meta{
      display:flex; gap:8px; flex-wrap:wrap; align-items:center;
    }
    .chip{
      display:inline-flex; align-items:center; gap:6px;
      padding:6px 10px; border-radius:999px;
      border:1px solid var(--line);
      background:#fff; color:var(--muted);
      font-weight:700; font-size:12px;
    }

    /* Table */
    .table{
      background:#fff;
      border-radius:12px;
      overflow:hidden;
    }
    .table thead th{
      background:#f8fafc;
      color:var(--ink);
      font-weight:800;
      border-bottom:1px solid var(--line) !important;
      white-space:nowrap;
    }
    .table tbody td{
      vertical-align:middle;
      font-weight:500;
      color:var(--ink-2);
    }
    .table tfoot th{
      font-weight:800;
      color:var(--ink);
      border-top:1px solid var(--line) !important;
      background:#fafafa;
    }
    .table > tbody > tr:hover{
      background:#fafafa;
    }

    /* Floating Print Button (action key highlighted) */
    .print-fab{
      position:fixed; right:14px; top:14px; z-index:9999;
      border-radius:999px; padding:10px 14px;
      box-shadow:0 16px 32px rgba(2,6,23,.22);
      background:var(--ok); color:#fff; border:none;
      font-weight:800; letter-spacing:.2px;
      display:inline-flex; align-items:center; gap:8px;
    }
    .print-fab:hover{ filter:brightness(.96); transform:translateY(-1px); }

    /* Helper */
    .subtle{
      color:var(--muted);
      font-weight:600;
      font-size:12px;
    }

    @media print{
      .print-hide{ display:none !important; }
      html, body{ background:#fff; }
      .box { box-shadow:none; border:1px solid #ddd; }
    }
  </style>
</head>
<body>
<section class="content">

  <!-- Floating Print Button (Action Key) -->
  <button class="print-fab print-hide" title="<?= e($_data['text_16'] ?? 'Print'); ?>"
          onclick="printContent('printable','Maintenance Report')">
    <i class="fa fa-print"></i> <?= e($_data['text_16'] ?? 'Print'); ?>
  </button>

  <div id="printable">
    <div style="margin:10px 6px 40px 6px;">
      <input type="hidden" id="web_url" value="<?= WEB_URL; ?>" />

      <?php include_once(ROOT_PATH.'partial/report_top_title.php'); ?>

      <div class="box box-success">
        <div class="box-header">
          <h3 class="box-title">
            <i class="fa fa-wrench"></i> Maintenance Report<?= $date_range_title; ?>
          </h3>
          <div class="meta print-hide">
            <?php if(!empty($get_data['bid'])): ?>
              <span class="chip" title="Filtered by Block">
                <i class="fa fa-building"></i> Block ID: <?= (int)$get_data['bid']; ?>
              </span>
            <?php endif; ?>
            <?php if(!empty($get_data['uid'])): ?>
              <span class="chip" title="Filtered by Unit">
                <i class="fa fa-home"></i> Unit ID: <?= (int)$get_data['uid']; ?>
              </span>
            <?php endif; ?>
            <?php if(!empty($start_date_filter) || !empty($end_date_filter)): ?>
              <span class="chip" title="Filtered by Date Range">
                <i class="fa fa-calendar"></i>
                <?= !empty($start_date_filter) ? e(date("jS F, Y", strtotime($start_date_filter))) : '…'; ?>
                 — <?= !empty($end_date_filter) ? e(date("jS F, Y", strtotime($end_date_filter))) : '…'; ?>
              </span>
            <?php endif; ?>
          </div>
        </div>

        <div class="box-body">
          <div class="subtle print-hide" style="margin-bottom:8px;">
            Showing latest maintenance activities. Use your browser’s print dialog for PDF export.
          </div>

          <div style="overflow:auto;">
            <table class="table sakotable table-bordered table-striped dt-responsive" style="font-size:13px; width:100%;">
              <thead>
                <tr>
                  <th>Maintenance Title</th>
                  <th>Maintenance Details</th>
                  <th>Type</th>
                  <th>Block</th>
                  <th>Unit</th>
                  <th>Date</th>
                  <th style="text-align:right;">Cost</th>
                </tr>
              </thead>
              <tbody>
              <?php
                if ($result && mysqli_num_rows($result) > 0):
                  while ($row = mysqli_fetch_assoc($result)):
                    $total_cost += (float)$row['m_amount'];
              ?>
                <tr>
                  <td><?= e($row['m_title']); ?></td>
                  <td><?= e($row['m_details']); ?></td>
                  <td><?= e(ucfirst($row['maintenance_type'])); ?></td>
                  <td><?= e($row['b_name'] ?? ''); ?></td>
                  <td><?= e($row['unit_no'] ?? ''); ?></td>
                  <td style="white-space:nowrap;"><?= date("jS F, Y", strtotime($row['m_date'])); ?></td>
                  <td style="text-align:right;"><?= money_print($row['m_amount']); ?></td>
                </tr>
              <?php
                  endwhile;
                else:
              ?>
                <tr>
                  <td colspan="7" style="text-align:center; color:#64748b;">No maintenance records found for the selected criteria.</td>
                </tr>
              <?php endif; mysqli_close($link); ?>
              </tbody>
              <tfoot>
                <tr>
                  <th colspan="6" style="text-align:right;">Total Cost</th>
                  <th style="text-align:right; color:#1e40af; font-size:1.1em;"><?= money_print($total_cost); ?></th>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

      </div>

    </div>
  </div>

</section>
</body>
</html>
