<?php

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

header('Content-Type: application/json; charset=utf-8');

function deleteEquipmentResponse(bool $success, string $message): void
{
    echo json_encode(
        [
            'success' => $success,
            'message' => $message
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit();
}

if (($_SESSION['role'] ?? '') !== 'admin') {
    deleteEquipmentResponse(false, 'Access denied.');
}

if (
    $_SERVER['REQUEST_METHOD'] !== 'POST' ||
    !hash_equals(
        $_SESSION['csrf_token'] ?? '',
        $_POST['csrf_token'] ?? ''
    )
) {
    deleteEquipmentResponse(false, 'Invalid request.');
}

$id = filter_var(
    $_POST['id'] ?? null,
    FILTER_VALIDATE_INT,
    ['options' => ['min_range' => 1]]
);

if ($id === false) {
    deleteEquipmentResponse(false, 'Invalid equipment.');
}

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$transactionStarted = false;

try {
    /*
    |--------------------------------------------------------------------------
    | Check whether equipment is used in a survey
    |--------------------------------------------------------------------------
    */

    $usageStatement = mysqli_prepare(
        $conn,
        'SELECT id
         FROM survey_equipment_details
         WHERE equipment_id = ?
         LIMIT 1'
    );

    mysqli_stmt_bind_param($usageStatement, 'i', $id);
    mysqli_stmt_execute($usageStatement);
    mysqli_stmt_store_result($usageStatement);

    $isUsed = mysqli_stmt_num_rows($usageStatement) > 0;

    mysqli_stmt_close($usageStatement);

    if ($isUsed) {
        deleteEquipmentResponse(
            false,
            'This equipment is already used in a survey and cannot be deleted.'
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Get current display order before deletion
    |--------------------------------------------------------------------------
    */

    $equipmentStatement = mysqli_prepare(
        $conn,
        'SELECT display_order
         FROM equipment_master
         WHERE id = ?
         LIMIT 1'
    );

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

    $equipmentResult = mysqli_stmt_get_result($equipmentStatement);
    $equipmentRow = mysqli_fetch_assoc($equipmentResult);

    mysqli_stmt_close($equipmentStatement);

    if (!$equipmentRow) {
        deleteEquipmentResponse(false, 'Equipment not found.');
    }

    $deletedOrder = (int)$equipmentRow['display_order'];

    /*
    |--------------------------------------------------------------------------
    | Delete equipment inside one transaction
    |--------------------------------------------------------------------------
    */

    mysqli_begin_transaction($conn);
    $transactionStarted = true;

    $assignmentDeleteStatement = mysqli_prepare(
        $conn,
        'DELETE FROM unit_equipment
         WHERE equipment_id = ?'
    );

    mysqli_stmt_bind_param(
        $assignmentDeleteStatement,
        'i',
        $id
    );

    mysqli_stmt_execute($assignmentDeleteStatement);
    mysqli_stmt_close($assignmentDeleteStatement);

    $equipmentDeleteStatement = mysqli_prepare(
        $conn,
        'DELETE FROM equipment_master
         WHERE id = ?'
    );

    mysqli_stmt_bind_param(
        $equipmentDeleteStatement,
        'i',
        $id
    );

    mysqli_stmt_execute($equipmentDeleteStatement);

    $deleted =
        mysqli_stmt_affected_rows($equipmentDeleteStatement) === 1;

    mysqli_stmt_close($equipmentDeleteStatement);

    if (!$deleted) {
        throw new RuntimeException('Equipment not found.');
    }

    /*
    |--------------------------------------------------------------------------
    | Close the display-order gap
    |--------------------------------------------------------------------------
    |
    | Example:
    | Delete order 2
    | 3 becomes 2
    | 4 becomes 3
    |
    */

    $reorderStatement = mysqli_prepare(
        $conn,
        'UPDATE equipment_master
         SET display_order = display_order - 1
         WHERE display_order > ?'
    );

    mysqli_stmt_bind_param(
        $reorderStatement,
        'i',
        $deletedOrder
    );

    mysqli_stmt_execute($reorderStatement);
    mysqli_stmt_close($reorderStatement);

    mysqli_commit($conn);
    $transactionStarted = false;

    deleteEquipmentResponse(
        true,
        'Equipment deleted successfully.'
    );
} catch (Throwable $exception) {
    if ($transactionStarted) {
        mysqli_rollback($conn);
    }

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

    if ($exception->getMessage() === 'Equipment not found.') {
        deleteEquipmentResponse(false, 'Equipment not found.');
    }

    deleteEquipmentResponse(
        false,
        'Unable to delete equipment. Please contact the administrator.'
    );
}