<?php

declare(strict_types=1);

date_default_timezone_set('Asia/Colombo');

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/role_filter.php';
require_once __DIR__ . '/../includes/activity_log.php';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/*
|--------------------------------------------------------------------------
| Request Validation
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: view_surveys.php');
    exit();
}

if (
    !hash_equals(
        $_SESSION['csrf_token'] ?? '',
        $_POST['csrf_token'] ?? ''
    )
) {
    $_SESSION['error_message'] = 'Invalid security token.';
    header('Location: view_surveys.php');
    exit();
}

$id = filter_input(
    INPUT_POST,
    'id',
    FILTER_VALIDATE_INT,
    [
        'options' => [
            'min_range' => 1
        ]
    ]
);

if (!$id) {
    $_SESSION['error_message'] = 'Invalid survey ID.';
    header('Location: view_surveys.php');
    exit();
}

/*
|--------------------------------------------------------------------------
| Verify Survey Access
|--------------------------------------------------------------------------
*/

$roleFilter = getSurveyRoleFilter('s');

$sql = "
    SELECT
        s.id,
        s.census_no,
        s.school_name
    FROM surveys s
    WHERE s.id = ?
    {$roleFilter['sql']}
    LIMIT 1
";

$stmt = mysqli_prepare($conn, $sql);

if (!$stmt) {
    $_SESSION['error_message'] = 'Unable to verify survey.';
    header('Location: view_surveys.php');
    exit();
}

$types = 'i' . $roleFilter['types'];

$params = array_merge(
    [$id],
    $roleFilter['params']
);

mysqli_stmt_bind_param(
    $stmt,
    $types,
    ...$params
);

mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);

$survey = mysqli_fetch_assoc($result);

mysqli_stmt_close($stmt);

if (!$survey) {
    $_SESSION['error_message'] = 'Survey not found or access denied.';
    header('Location: view_surveys.php');
    exit();
}

/*
|--------------------------------------------------------------------------
| Delete Survey
|--------------------------------------------------------------------------
*/

try {

    mysqli_begin_transaction($conn);

    /*
    ---------------------------------------------------------
    Delete Other Unit Equipment
    ---------------------------------------------------------
    */

    $stmt = mysqli_prepare(
        $conn,
        "
        DELETE soe
        FROM survey_other_equipment soe
        INNER JOIN survey_other_units sou
            ON sou.id = soe.other_unit_id
        WHERE sou.survey_id = ?
        "
    );

    mysqli_stmt_bind_param($stmt, 'i', $id);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

    /*
    ---------------------------------------------------------
    Delete Other Units
    ---------------------------------------------------------
    */

    $stmt = mysqli_prepare(
        $conn,
        "
        DELETE FROM survey_other_units
        WHERE survey_id = ?
        "
    );

    mysqli_stmt_bind_param($stmt, 'i', $id);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

    /*
    ---------------------------------------------------------
    Delete Standard Equipment
    ---------------------------------------------------------
    */

    $stmt = mysqli_prepare(
        $conn,
        "
        DELETE FROM survey_equipment_details
        WHERE survey_id = ?
        "
    );

    mysqli_stmt_bind_param($stmt, 'i', $id);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

    /*
    ---------------------------------------------------------
    Delete Survey
    ---------------------------------------------------------
    */

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

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

    if (mysqli_stmt_affected_rows($stmt) !== 1) {
        mysqli_stmt_close($stmt);

        throw new RuntimeException(
            'The survey could not be deleted.'
        );
    }

    mysqli_stmt_close($stmt);

    mysqli_commit($conn);

    logActivity(
        $conn,
        'Survey Management',
        'Delete Survey',
        'Survey deleted for "' .
        (string)$survey['school_name'] .
        '" (Census No: ' .
        (string)$survey['census_no'] .
        ')'
    );

    $_SESSION['success_message'] =
        'Survey deleted successfully.';
} catch (Throwable $exception) {

    mysqli_rollback($conn);

    error_log(
        'Survey delete error: ' .
        $exception->getMessage()
    );

    $_SESSION['error_message'] =
        'Unable to delete the survey.';
}

header('Location: view_surveys.php');
exit();