<?php

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

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

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

/*
|--------------------------------------------------------------------------
| Filters
|--------------------------------------------------------------------------
*/
$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
|--------------------------------------------------------------------------
*/
$default_fields = [
    'district',
    'zone_name',
    'division_name'
];

/*
|--------------------------------------------------------------------------
| Final Selected Fields
|--------------------------------------------------------------------------
*/
$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'];
    }
}

/*
|--------------------------------------------------------------------------
| Build Filter Query
|--------------------------------------------------------------------------
*/
$where = [];

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

if (!empty($zone))
{
    $zone = mysqli_real_escape_string($conn, $zone);
    $where[] = "zone_name = '$zone'";
}

if (!empty($division))
{
    $division = mysqli_real_escape_string($conn, $division);
    $where[] = "division_name = '$division'";
}

$where_sql = "";

if (!empty($where))
{
    $where_sql = "WHERE " . implode(" AND ", $where);
}

/*
|--------------------------------------------------------------------------
| Get Survey Data
|--------------------------------------------------------------------------
*/
$sql =
"SELECT id," .
implode(",", $selected_fields) .
" FROM surveys
 $where_sql
 ORDER BY survey_date DESC";

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

if (!$result)
{
    die(
        "Database Error: " .
        mysqli_error($conn)
    );
}

?>

<!DOCTYPE html>
<html>
<head>

<title>Survey Print Report</title>

<style>

body{
font-family:Arial,sans-serif;
margin:20px;
}

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

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

th,td{
border:1px solid #000;
padding:8px;
font-size:12px;
text-align:center;
}

th{
background:#f0f0f0;
}

@media print{
button{
display:none;
}
}

</style>

</head>

<body>

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

<table>

<thead>

<tr>

<?php foreach($selected_fields as $field){ ?>

<th>
<?= ucwords(str_replace('_',' ',$field)) ?>
</th>

<?php } ?>

<?php foreach($equipment_names as $eq_name){ ?>

<th><?= htmlspecialchars($eq_name) ?> Working</th>
<th><?= htmlspecialchars($eq_name) ?> Not Working</th>

<?php } ?>

</tr>

</thead>

<tbody>

<?php while($survey = mysqli_fetch_assoc($result)){ ?>

<tr>

<?php foreach($selected_fields as $field){ ?>

<td>
<?= htmlspecialchars($survey[$field] ?? '') ?>
</td>

<?php } ?>

<?php 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);
?>

<td>
<?= $eq_data['working'] ?? 0 ?>
</td>

<td>
<?= $eq_data['not_working'] ?? 0 ?>
</td>

<?php } ?>

</tr>

<?php } ?>

</tbody>

</table>

<br>

<button onclick="window.print()">
Print Report
</button>

</body>
</html>