<?php

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../vendor/autoload.php';

/*
|--------------------------------------------------------------------------
| Access Control
|--------------------------------------------------------------------------
*/

if (
    !isset($_SESSION['role']) ||
    !in_array($_SESSION['role'], ['admin', 'zonal_director'])
)
{
    die("Access Denied");
}

use Dompdf\Dompdf;

$district = trim($_GET['district'] ?? 'ALL');
$zone     = trim($_GET['zone'] ?? '');
$division = trim($_GET['division'] ?? '');

$fields    = $_GET['fields'] ?? [];
$equipment = $_GET['equipment'] ?? [];

if (
    empty($district) &&
    empty($zone) &&
    empty($division)
)
{
    die("Please select at least one filter.");
}

$default_fields = [
    'district',
    'zone_name',
    'division_name'
];

$selected_fields = array_unique(
    array_merge($default_fields, $fields)
);

/*
|--------------------------------------------------------------------------
| Equipment Names
|--------------------------------------------------------------------------
*/
$equipment_names = [];

if (!empty($equipment))
{
    $ids = implode(",", array_map('intval', $equipment));

    $eq_query = mysqli_query(
        $conn,
        "SELECT id, equipment_name
         FROM equipment_master
         WHERE id IN ($ids)"
    );

    while($eq = mysqli_fetch_assoc($eq_query))
    {
        $equipment_names[$eq['id']] = $eq['equipment_name'];
    }
}

/*
|--------------------------------------------------------------------------
| Filters
|--------------------------------------------------------------------------
*/
$where = [];

if (!empty($district) && $district !== 'ALL')
{
    $where[] =
        "district='" .
        mysqli_real_escape_string($conn,$district) .
        "'";
}
if ($zone) $where[] = "zone_name='" . mysqli_real_escape_string($conn,$zone) . "'";
if ($division) $where[] = "division_name='" . mysqli_real_escape_string($conn,$division) . "'";

$where_sql = $where ? "WHERE " . implode(" AND ", $where) : "";

$sql =
"SELECT id," .
implode(",", $selected_fields) .
" FROM surveys
 $where_sql
 ORDER BY survey_date DESC";

$result = mysqli_query($conn, $sql);

/*
|--------------------------------------------------------------------------
| Build HTML
|--------------------------------------------------------------------------
*/

$html = '
<style>

@page{
    size:A3 landscape;
    margin:5px;
}

body{
    font-family:Arial,sans-serif;
    font-size:8px;
}

h2{
    text-align:center;
    margin-bottom:10px;
}

table{
    width:100%;
    border-collapse:collapse;
    table-layout:fixed;
}

th,td{
    border:1px solid #000;
    padding:2px;
    font-size:7px;
    text-align:center;
    word-break:break-word;
}

th{
    background:#eeeeee;
}

</style>

<h2>Sabaragamuwa Province School Computer Lab Survey Report</h2>

<table>

<tr>';

foreach($selected_fields as $field)
{
    $html .= "<th>" . ucwords(str_replace('_',' ', $field)) . "</th>";
}

foreach($equipment_names as $eq_name)
{
    $html .= "<th>{$eq_name} Working</th>";
    $html .= "<th>{$eq_name} Not Working</th>";
}

$html .= "</tr>";

while($survey = mysqli_fetch_assoc($result))
{
    $html .= "<tr>";

    foreach($selected_fields as $field)
    {
        $value = htmlspecialchars($survey[$field] ?? '');

            if(strlen($value) > 15)
            {
                $value = substr($value, 0, 15) . "...";
            }

            $html .= "<td>$value</td>";
    }

    foreach($equipment_names as $eq_id => $eq_name)
    {
        $eq_result = mysqli_query(
            $conn,
            "SELECT working, not_working
             FROM survey_equipment
             WHERE survey_id=" . (int)$survey['id'] . "
             AND equipment_id=" . (int)$eq_id
        );

        $eq_data = mysqli_fetch_assoc($eq_result);

        $html .= "<td>" . ($eq_data['working'] ?? 0) . "</td>";
        $html .= "<td>" . ($eq_data['not_working'] ?? 0) . "</td>";
    }

    $html .= "</tr>";
}

$html .= "</table>";

/*
|--------------------------------------------------------------------------
| Generate PDF
|--------------------------------------------------------------------------
*/
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A3', 'landscape');
$dompdf->render();
$dompdf->stream("survey_report.pdf", ["Attachment" => true]);
exit;
?>

