<?php

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid Request");
}

$id = (int)($_POST['id'] ?? 0);

if ($id <= 0) {
    die("Invalid Survey ID");
}

/*
|--------------------------------------------------------------------------
| SECURITY CHECK
|--------------------------------------------------------------------------
*/
$role = $_SESSION['role'];
$username = $_SESSION['fullname'];

$check = mysqli_prepare($conn, "SELECT entered_by FROM surveys WHERE id=?");
mysqli_stmt_bind_param($check, "i", $id);
mysqli_stmt_execute($check);

$res = mysqli_stmt_get_result($check);
$row = mysqli_fetch_assoc($res);

if (!$row) {
    die("Survey not found");
}

if ($role != 'admin' && $row['entered_by'] != $username) {
    die("Access Denied");
}

/*
|--------------------------------------------------------------------------
| UPDATE SURVEY TABLE
|--------------------------------------------------------------------------
*/
$stmt = mysqli_prepare($conn, "
    UPDATE surveys SET
        school_name=?,
        district=?,
        zone_name=?,
        division_name=?,
        principal_name=?,
        principal_phone=?,
        school_phone=?,
        it_teacher_name=?,
        it_teacher_phone=?
    WHERE id=?
");

mysqli_stmt_bind_param(
    $stmt,
    "sssssssssi",
    $_POST['school_name'],
    $_POST['district'],
    $_POST['zone_name'],
    $_POST['division_name'],
    $_POST['principal_name'],
    $_POST['principal_phone'],
    $_POST['school_phone'],
    $_POST['it_teacher_name'],
    $_POST['it_teacher_phone'],
    $id
);

mysqli_stmt_execute($stmt);

/*
|--------------------------------------------------------------------------
| UPDATE EQUIPMENT
|--------------------------------------------------------------------------
*/
$working = $_POST['working'] ?? [];
$not_working = $_POST['not_working'] ?? [];

/* Get existing equipment rows */
$existing = [];
$res = mysqli_query($conn, "SELECT equipment_id FROM survey_equipment WHERE survey_id=$id");

while ($r = mysqli_fetch_assoc($res)) {
    $existing[$r['equipment_id']] = true;
}

foreach ($working as $eq_id => $w_value) {

    $eq_id = (int)$eq_id;
    $w_value = (int)$w_value;
    $nw_value = (int)($not_working[$eq_id] ?? 0);

    if (isset($existing[$eq_id])) {

        // UPDATE
        $upd = mysqli_prepare($conn, "
            UPDATE survey_equipment
            SET working=?, not_working=?
            WHERE survey_id=? AND equipment_id=?
        ");

        mysqli_stmt_bind_param($upd, "iiii", $w_value, $nw_value, $id, $eq_id);
        mysqli_stmt_execute($upd);

    } else {

        // INSERT
        $ins = mysqli_prepare($conn, "
            INSERT INTO survey_equipment
            (survey_id, equipment_id, working, not_working)
            VALUES (?,?,?,?)
        ");

        mysqli_stmt_bind_param($ins, "iiii", $id, $eq_id, $w_value, $nw_value);
        mysqli_stmt_execute($ins);
    }
}

/*
|--------------------------------------------------------------------------
| DONE
|--------------------------------------------------------------------------
*/
header("Location: view_surveys.php?id=$id&updated=1");
exit();