<?php

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

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$id) {
    die("Invalid Survey ID");
}

/*
|--------------------------------------------------------------------------
| GET SURVEY OWNER
|--------------------------------------------------------------------------
*/

$stmt = mysqli_prepare(
    $conn,
    "SELECT entered_by FROM surveys WHERE id = ?"
);

mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);
$survey = mysqli_fetch_assoc($result);

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

/*
|--------------------------------------------------------------------------
| AUTH CHECK (ADMIN OR OWNER ONLY)
|--------------------------------------------------------------------------
*/

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

/*
|--------------------------------------------------------------------------
| DELETE TRANSACTION (SAFE WAY)
|--------------------------------------------------------------------------
*/

mysqli_begin_transaction($conn);

try {

    /*
    | Delete equipment first
    */
    $stmt1 = mysqli_prepare(
        $conn,
        "DELETE FROM survey_equipment WHERE survey_id = ?"
    );

    mysqli_stmt_bind_param($stmt1, "i", $id);
    mysqli_stmt_execute($stmt1);

    /*
    | Delete main survey
    */
    $stmt2 = mysqli_prepare(
        $conn,
        "DELETE FROM surveys WHERE id = ?"
    );

    mysqli_stmt_bind_param($stmt2, "i", $id);
    mysqli_stmt_execute($stmt2);

    /*
    | Commit changes
    */
    mysqli_commit($conn);

    header("Location: view_surveys.php?deleted=1");
    exit();

} catch (Exception $e) {

    mysqli_rollback($conn);
    die("Delete Failed: " . $e->getMessage());
}