<?php 
session_start();
include '../../connection.php';
$id = $_SESSION['user_id'];
?>
<div class=" my-4">
  <?php 
  if (isset($_SESSION['role']) && $_SESSION['role'] === "admin") {
    ?>
 <button id="generate-report" class="btn btn-dark btn-lg">
    Generate Report <i class="fa fa-cogs"></i>
  </button>
    <?php

  }
  ?>
 

  <div id="loading" style="display:none;" class="mt-3">
 <button id="download-btn" class="btn btn-primary"> Generate Report</button>
<div id="loading" style="display:none;"><i class="fa fa-spinner text-white" aria-hidden="true"></i> Please wait, generating Excel...</div>

  </div>

  <div id="download-link" style="display:none;" class="mt-3">
    <a id="download-report" href="#" class="btn btn-primary btn-lg" download>
      ⬇️ Download Barangay_Report.xlsx
    </a>
  </div>
</div>

<?php if (isset($_SESSION['role']) && $_SESSION['role'] === "official"): ?>
  <div class="row">
    <div class="col-md-3">
      <div class="card">
        <div class="card-body">
          <h5>Assigned complaint</h5>
          <?php
          $query = "SELECT count(*) as total_assignment FROM `tbl_assignment` WHERE  assigned_person = '$id'";
          $query_result  = $conn->query($query);
          $row = $query_result->fetch_assoc();
           ?>
          <h4><?= $row['total_assignment'] ?></h4>
        </div>
      </div>
    </div>

       <div class="col-md-3">
      <div class="card">
        <div class="card-body">
          <h5>Total pending</h5>
            <?php
          $query = "SELECT count(*) as total_pending FROM `tbl_assignment` WHERE  assigned_person AND status = 'Pending'";
          $query_result  = $conn->query($query);
          $row = $query_result->fetch_assoc();
           ?>
          <h4><?= $row['total_pending'] ?></h4>
        </div>
      </div>
    </div>

       <div class="col-md-3">
      <div class="card">
        <div class="card-body">
          <h5>Total pending</h5>
          <?php
         $query = "SELECT count(*) as total_completed FROM `tbl_assignment` WHERE  assigned_person AND status = 'Completed'";
          $query_result  = $conn->query($query);
          $row = $query_result->fetch_assoc();
           ?>
          <h4><?= $row['total_completed'] ?></h4>
        </div>
      </div>
    </div>

       <div class="col-md-3">
      <div class="card">
        <div class="card-body">
          <h5>Total Hearing</h5>
            <?php
         $query = "SELECT count(*) as total_ongoing FROM `tbl_assignment` WHERE  assigned_person AND status = 'Ongoing'";
          $query_result  = $conn->query($query);
          $row = $query_result->fetch_assoc();
           ?>
          <h4><?= $row['total_ongoing'] ?></h4>
        </div>
      </div>
    </div>
  </div>
<?php endif ?>

<?php if (isset($_SESSION['role']) && $_SESSION['role'] === "admin"): ?>
  

<!-- Statistics Cards -->
<div class="row">
  <div class="col-xl-3 col-md-6 mb-4">
    <div class="card stat-card bg-residents">
      <div class="card-body">
        <i class="fas fa-users"></i>
        <?php 
        $query = "SELECT COUNT(*) AS total_resident FROM tbl_resident";
        $result = $conn->query($query);
        $row = $result->fetch_assoc();
        ?>
        <div class="count"><?= number_format($row['total_resident']) ?></div>
        <div class="label">Total Residents</div>
      </div>
    </div>
  </div>

  <div class="col-xl-3 col-md-6 mb-4">
    <div class="card stat-card bg-households">
      <div class="card-body">
        <i class="fas fa-home"></i>
        <?php 
        $query = "SELECT COUNT(*) AS total_transaction FROM tbl_transaction";
        $result = $conn->query($query);
        $row = $result->fetch_assoc();
        ?>
        <div class="count"><?= number_format($row['total_transaction']) ?></div>
        <div class="label">Total Complaints Received</div>
      </div>
    </div>
  </div>

  <div class="col-xl-3 col-md-6 mb-4">
    <div class="card stat-card bg-officials">
      <div class="card-body">
        <i class="fas fa-user-tie"></i>
        <?php 
        $query = "SELECT COUNT(*) AS total_official FROM tbl_user WHERE role_type = 'official'";
        $result = $conn->query($query);
        $row = $result->fetch_assoc();
        ?>
        <div class="count"><?= number_format($row['total_official']) ?></div>
        <div class="label">Barangay Officials</div>
      </div>
    </div>
  </div>

  <div class="col-xl-3 col-md-6 mb-4">
    <div class="card stat-card bg-requests">
      <div class="card-body">
        <i class="fas fa-file-alt"></i>
        <?php 
        $query = "SELECT COUNT(*) AS total_pending_complaint FROM tbl_transaction WHERE status = 'pending'";
        $result = $conn->query($query);
        $row = $result->fetch_assoc();
        ?>
        <div class="count"><?= number_format($row['total_pending_complaint']) ?></div>
        <div class="label">Pending</div>
      </div>
    </div>
  </div>
</div>
<div class="row mb-3">
  <div class="col-md-6">
    <!-- chart 1 -->
    <div class="card">
      <div class="card-header">Status Breakdown</div>
      <div class="card-body">
         <canvas id="status_breakdown" style="height: 100%;"></canvas>
      </div>
    </div>
   
  </div>
   <div class="col-md-6">
    <!-- chart 2 -->
    <div class="card">
      <div class="card-header">Resolved Complaints</div>
      <div class="card-body">
           <canvas id="resolved_complaints" style="height: 100%;"></canvas>
      </div>
    </div>

  </div>
  
</div>


<!-- Charts and Tables -->
<div class="row">
  <!-- Complaints Chart -->
  <div class="col-lg-8 mb-4">

    <div class="card">
      <div class="card-header">Most Complaints Per Month</div>
      <div class="card-body">
        <div class="chart-container">
          <canvas id="myChart"></canvas>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="card-header">
       <nav class="nav justify-content-center mb-3">
  <a class="nav-link m-2 btn btn-dark btn-sm switch-table active" data-status="Pending">Pending</a>
      <a class="nav-link m-2 btn btn-dark btn-sm switch-table" data-status="Accept">Accepted</a>
      <a class="nav-link m-2 btn btn-dark btn-sm switch-table" data-status="Settled">Settled</a>
      <a class="nav-link m-2 btn btn-dark btn-sm switch-table" data-status="Unsettled">Unsettled</a>
      <a class="nav-link m-2 btn btn-dark btn-sm switch-table" data-status="Declined">Declined</a>
    </nav>

      </div>
      <div class="card-body">
       <div id="transactions_statuses"></div>
      </div>
    </div>

  </div>

  <!-- Barangay Officials -->
  <div class="col-lg-4 mb-4">
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <span>Barangay Officials</span>
        <a href="#" class="btn btn-sm btn-primary click_page" data-page="organizational_structure.php">View All</a>
      </div>
      <div class="card-body">
        <div class="table-responsive" id="officials"></div>
      </div>
    </div>
  </div>
</div>
<?php endif ?>


<script>
  load_breakdown_status();
  load_resolved_complaints();
function load_breakdown_status() {
  const breakdown = document.getElementById('status_breakdown');

  $.ajax({
    method: 'POST',
    url: 'query/dashboard_query.php',
    data: { "loading_status_breakdown": 1 },
    dataType: 'json',
    success: function(res) {
      // ✅ Parse the result arrays
      const statusLabels = res.status_label;
      const totalCounts = res.total_label;

      new Chart(breakdown, {
        type: 'pie',
        data: {
          labels: statusLabels,
          datasets: [{
            label: 'Status Breakdown',
            data: totalCounts,
            borderWidth: 1,
            backgroundColor: ['#f87171', '#60a5fa', '#34d399', '#fbbf24'] // optional colors
          }]
        },
        options: {
          responsive: true,
          plugins: {
            legend: { position: 'bottom' }
          }
        }
      });
    }
  });
}


    
function load_resolved_complaints() {
  const resolved_complaints = document.getElementById('resolved_complaints');

  $.ajax({
    method: 'POST',
    url: 'query/dashboard_query.php',
    data: {
      'loading_resolved_complaints': 1
    },
    dataType: 'json', // ✅ Important
    success: function(res) {
      const complaint_total = res.complaint_total;
      const complaint_type = res.complaint_name;

      new Chart(resolved_complaints, {
        type: 'bar',
        data: {
          labels: complaint_type,
          datasets: [{
            label: '# of Resolved Complaints',
            data: complaint_total,
            backgroundColor: '#60a5fa',
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
         scales: {
            y: {
              beginAtZero: true,
              ticks: {
                stepSize: 1, // ✅ ensures increment by 1
                callback: function(value) {
                  return Number.isInteger(value) ? value : ''; // ✅ hide decimals
                }
              }
            }
          },
        }
      });
    }
  });
}



$('#generate-report').on('click', function () {
  // Hide the generate button and download link
  $('#generate-report').hide();
  $('#download-link').hide();

  // Show spinner with proper HTML
  $('#loading')
    .show()
    .html('<i class="fa fa-spinner fa-spin text-white" aria-hidden="true"></i> Generating Excel... Please wait.');

  // Perform AJAX request
  $.ajax({
    url: 'query/export_all_reports.php',
    type: 'POST',
    data: { generate: 1 },
    dataType: 'json',
    success: function (res) {
      if (res.status === 'success') {
        $('#loading').html('<div class="alert alert-success" role="alert">Report generated successfully!</div>');
        $('#download-link').show();
        $('#download-report').attr('href', res.file);
      } else {
        $('#loading').html('<div class="alert alert-danger" role="alert">Failed to generate report. Try again.</div>');
      }
      $('#generate-report').show(); // Re-show button after process
    },
    error: function () {
      $('#loading').html('<div class="alert alert-danger" role="alert">Server error. Please try again.</div>');
      $('#generate-report').show(); // Re-show button even on error
    }
  });
});




//  Listen for status tab/button click
$(document).on('click', '.switch-table', function () {
  let status = $(this).data("status");
  load_transaction_status(status);
});

// 📌 Load default on page load
$(document).ready(function () {
  load_transaction_status("Pending");
});

// ✅ Function to load transactions by status
function load_transaction_status(status) {
  $.ajax({
    method: 'POST',
    url: 'query/dashboard_query.php',
    data: {
      loading_transactions_status: 1,
      status: status
    },
    beforeSend: function () {
      // Optional: show loader/spinner while loading
      $('#transactions_statuses').html('<p class="text-center text-muted">Loading...</p>');
    },
    success: function (res) {
      $('#transactions_statuses').html(res);
    },
    error: function (xhr, status, error) {
      console.error("AJAX Error:", error);
      $('#transactions_statuses').html('<p class="text-danger">Failed to load data.</p>');
    }
  });
}


  // ✅ Load officials table
  function load_all_officials(){
    $.ajax({
      method: 'post',
      url: 'query/dashboard_query.php',
      data: { "loading_all_officials": 1 },
      success: function(res){
        $('#officials').html(res);
      }
    });
  }
  load_all_officials();
load_most_complaints_per_month();
function load_most_complaints_per_month() {
  const ctx = document.getElementById('myChart');

  $.ajax({
    method: 'post',
    url: 'query/dashboard_query.php',
    data: { "most_complaints_per_month": 1 },
    dataType: 'json',
    success: function(res) {
      const labels = res.map(item => item.month_label);
      const data = res.map(item => item.total_complaints);
      const complaintNames = res.map(item => item.complain_name);

      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: 'Most Complained Issue',
            data: data,
            backgroundColor: '#3498db',
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          scales: {
            y: {
              beginAtZero: true,
              ticks: {
                stepSize: 1, // ✅ ensures increment by 1
                callback: function(value) {
                  return Number.isInteger(value) ? value : ''; // ✅ hide decimals
                }
              }
            }
          },
          plugins: {
            tooltip: {
              callbacks: {
                label: function(context) {
                  return `${complaintNames[context.dataIndex]}: ${context.parsed.y} complaints`;
                }
              }
            }
          }
        }
      });
    }
  });
}

  
</script>
