<?php
// pages/kagawad_reports.php
session_start();
include '../../connection.php';

// Ensure user logged in (optional, but recommended)
if (!isset($_SESSION['user_id'])) {
    // redirect to login or show message
    exit('Unauthorized');
}

// Load kagawads for the filter (optional: only users in org structure with position KAGAWADS)
$kagawads = [];
$kq = "
  SELECT u.user_id, CONCAT(u.first_name, ' ', u.last_name) AS fullname
  FROM tbl_user u
  JOIN tbl_organizational_structure o ON o.user_id = u.user_id
  WHERE o.position = 'KAGAWADS' AND o.status = 'Active'
  ORDER BY u.first_name
";
if ($res = $conn->query($kq)) {
    while ($r = $res->fetch_assoc()) $kagawads[] = $r;
    $res->free();
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Kagawad Status Reports</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">

  <!-- Add Bootstrap / FontAwesome / jQuery CDN or your local copies -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.6.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

  <style>
    /* your CSS (kept and slightly cleaned) */
    .card { border: none; border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); margin-bottom: 20px; transition: transform 0.3s; }
    .card:hover { transform: translateY(-5px); }
    .card-header { background-color: white; border-bottom: 1px solid #eee; border-radius: 10px 10px 0 0 !important; padding: 15px 20px; font-weight: 600; }
    .status-badge { padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
    .status-pending { background-color: rgba(243, 156, 18, 0.15); color: #b06c0f; }
    .status-in-progress { background-color: rgba(52, 152, 219, 0.12); color: #1a5a8a; }
    .status-resolved { background-color: rgba(39, 174, 96, 0.12); color: #1a6b3a; }
    .status-urgent { background-color: rgba(231, 76, 60, 0.12); color: #a83224; }
    .kagawad-avatar { width: 45px; height: 45px; border-radius: 50%; object-fit: cover; border: 2px solid #eee; }
    .resident-avatar { width: 35px; height: 35px; border-radius: 50%; object-fit: cover; border: 2px solid #eee; }
    .report-item { border-bottom: 1px solid #eee; padding: 15px 0; transition: background-color 0.2s; }
    .report-item:hover { background-color: #f8f9fa; }
    .report-item:last-child { border-bottom: none; }
    .priority-indicator { width: 10px; height: 10px; border-radius: 50%; display: inline-block; margin-right: 5px; }
    .progress-sm { height: 8px; }
    .timeline { position: relative; padding-left: 30px; }
    .timeline::before { content: ''; position: absolute; left: 10px; top: 0; bottom: 0; width: 2px; background-color: #dee2e6; }
    .timeline-item { position: relative; margin-bottom: 20px; }
    .timeline-item::before { content: ''; position: absolute; left: -20px; top: 5px; width: 12px; height: 12px; border-radius: 50%; background-color: var(--secondary); }
    .action-btn { padding: 5px 10px; font-size: 0.85rem; margin-right: 5px; margin-bottom: 5px; }
  </style>
</head>
<body>
<div class="container-fluid mt-4">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h2 class="mb-1">Kagawad Status Reports</h2>
      <p class="text-muted mb-0">Monitor reports submitted by kagawads on assigned complaints</p>
    </div>
  </div>

  <!-- Filters -->
  <div class="card mb-4">
    <div class="card-body">
      <div class="row">
        <div class="col-lg-9">
          <div class="form-inline">
            <div class="form-group mr-3 mb-2">
              <label for="kagawadFilter" class="mr-2">Kagawad:</label>
              <select class="form-control" id="kagawadFilter">
                <option value="all">All Kagawads</option>
                <?php foreach ($kagawads as $k): ?>
                  <option value="<?= htmlspecialchars($k['user_id']) ?>"><?= htmlspecialchars($k['fullname']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="form-group mr-3 mb-2">
              <label for="statusFilter" class="mr-2">Status:</label>
              <select class="form-control" id="statusFilter">
                <option value="all">All Status</option>
                <option value="Accept">Accept</option>
                <option value="Pending">Pending</option>
                <option value="Declined">Declined</option>
                <option value="Settled">Settled</option>
                <option value="Unsettled">Unsettled</option>
              </select>
            </div>

            <div class="form-group mb-2">
              <label for="dateFrom" class="mr-2">Date Range:</label>
              <input type="date" class="form-control mr-2" id="dateFrom">
              <span class="mr-2">to</span>
              <input type="date" class="form-control" id="dateTo">
            </div>
          </div>
        </div>

        <div class="col-lg-3 mt-2 mt-lg-0">
          <div class="input-group">
            <input type="text" class="form-control" id="searchReports" placeholder="Search reports...">
            <div class="input-group-append">
              <button class="btn btn-outline-secondary" id="searchBtn" type="button">
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Kagawad Performance (static example cards) -->
  <div class="card mb-4">
    <div class="card-header"><h5 class="mb-0">Kagawad Performance Overview</h5></div>
    <div class="card-body">
      <div class="row">
        <!-- Example: these can be generated from DB similarly -->
        <?php
// Get all Kagawads with their assignment counts and resolved counts
$kperf_q = "
  SELECT 
      u.user_id,
      CONCAT(u.first_name, ' ', u.last_name) AS fullname,
      COUNT(a.assignment_id) AS assigned_count,
      SUM(CASE WHEN t.status IN ('Resolved', 'Settled', 'Accept') THEN 1 ELSE 0 END) AS resolved_count
  FROM tbl_user u
  JOIN tbl_organizational_structure o ON o.user_id = u.user_id
  LEFT JOIN tbl_assignment a ON a.assigned_person = u.user_id
  LEFT JOIN tbl_transaction t ON t.UniqueID = a.UniqueID
  WHERE o.position = 'KAGAWADS'
  GROUP BY u.user_id
  ORDER BY fullname ASC

";

$result = $conn->query($kperf_q);
if ($result && $result->num_rows > 0):
  while ($row = $result->fetch_assoc()):
    $assigned = (int)$row['assigned_count'];
    $resolved = (int)$row['resolved_count'];
    $pct = $assigned > 0 ? round(($resolved / $assigned) * 100) : 0;

    // determine bar color
    if ($pct >= 70) {
        $barClass = 'bg-success';
    } elseif ($pct >= 40) {
        $barClass = 'bg-warning';
    } else {
        $barClass = 'bg-danger';
    }

    // avatar
    $avatar = 'https://ui-avatars.com/api/?name=' . urlencode($row['fullname']) . '&background=3498db&color=fff';
?>
    <div class="col-md-12 mb-3">
      <div class="d-flex align-items-center">
        <img src="<?= $avatar ?>" class="kagawad-avatar mr-3" alt="Kagawad Avatar">
        <div class="flex-grow-1">
          <h6 class="mb-1"><?= htmlspecialchars($row['fullname']) ?></h6>
          <div class="kagawad-progress">
            <div class="d-flex justify-content-between">
              <small>Assigned: <?= $assigned ?></small>
              <small>Resolved: <?= $resolved ?></small>
            </div>
            <div class="progress progress-sm">
              <div class="progress-bar <?= $barClass ?>" role="progressbar" style="width: <?= $pct ?>%;"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
<?php
  endwhile;
else:
  echo "<div class='text-muted'>No Kagawads found.</div>";
endif;
?>

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

  <!-- Reports List -->
  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <h5 class="mb-0">Recent Kagawad Reports</h5>
      <div class="btn-group btn-group-sm">
        <button class="btn btn-outline-secondary active" id="filterAll">All Reports</button>
        <button class="btn btn-outline-secondary" id="filterWeek">This Week</button>
        <button class="btn btn-outline-secondary" id="filterUnreviewed">Unreviewed</button>
      </div>
    </div>
    <div class="card-body">
      <div id="reports-list">Loading...</div>
    </div>
  </div>
</div>

<!-- jQuery / Bootstrap / Popper -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.6.2/js/bootstrap.min.js"></script>

<script>
$(function () {
    // initial load
    load_report_list();

    // filters & search
    $('#kagawadFilter, #statusFilter, #dateFrom, #dateTo').on('change', load_report_list);
    $('#searchReports').on('keyup', function (e) {
        // small debounce
        clearTimeout($.data(this, 'timer'));
        var wait = setTimeout(load_report_list, 300);
        $(this).data('timer', wait);
    });
    $('#searchBtn').on('click', load_report_list);

    // quick filter buttons
    $('#filterWeek').on('click', function() {
        // set dateFrom to 7 days ago, dateTo to today
        var today = new Date().toISOString().slice(0,10);
        var last7 = new Date(); last7.setDate(last7.getDate()-7);
        $('#dateFrom').val(last7.toISOString().slice(0,10));
        $('#dateTo').val(today);
        load_report_list();
    });
    $('#filterAll').on('click', function(){
        $('#dateFrom').val('');
        $('#dateTo').val('');
        load_report_list();
    });
    $('#filterUnreviewed').on('click', function(){
        $('#statusFilter').val('Pending');
        load_report_list();
    });

    // Approve report (delegated)
    $(document).on('click', '.approve-report', function () {
        var reportId = $(this).data('id');
        if (!reportId) return;
       
        $.post('query/reports_query.php', { approve_report: 1, report_id: reportId }, function (resp) {
            // simple feedback
            // alert(resp.message || resp);
            load_report_list();
        }, 'json').fail(function(xhr) {
            alert('Request failed: ' + xhr.responseText);
        });
    });
});

function load_report_list() {
    $('#reports-list').html('<div class="text-center py-3"><i class="fas fa-spinner fa-spin me-2"></i> Loading reports...</div>');
    $.ajax({
        url: 'query/reports_query.php',
        method: 'POST',
        dataType: 'html',
        data: {
            loading_reports_list: 1,
            kagawad: $('#kagawadFilter').val(),
            status: $('#statusFilter').val(),
            dateFrom: $('#dateFrom').val(),
            dateTo: $('#dateTo').val(),
            search: $('#searchReports').val()
        },
        success: function (html) {
            $('#reports-list').html(html);
        },
        error: function (xhr) {
            $('#reports-list').html('<div class="alert alert-danger">Failed to load reports.</div>');
            console.error(xhr.responseText);
        }
    });
}
</script>
</body>
</html>
