<?php
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}

// Get POST data
$assignment_id = $_POST['assignment_id'];
$surveyor_id = $_POST['surveyor_id'];
$client_id = $_POST['client_id'];
$client_name = $_POST['client_name'];  // Get the client name from the POST data
$status = $_POST['status']; // 'Completed', 'Not Started', 'In Progress', etc.

// Function to remove from admin_assignments
function removeAdminAssignment($con, $assignment_id) {
    $sql = "DELETE FROM admin_assignments WHERE id = ?";
    $stmt = $con->prepare($sql);
    $stmt->bind_param('i', $assignment_id);

    if (!$stmt->execute()) {
        echo 'error';
        $stmt->close();
        return false;
    }
    $stmt->close();
    return true;
}

// If "Pause" is selected, update the surveyor assignments and remove from admin_assignments
if (isset($_POST['pause_surveyor_client']) && $_POST['pause_surveyor_client'] === 'true') {
    // Update surveyor_assignments to set status to 0
    $sql_pause_surveyor = "UPDATE surveyor_assignments SET status = 0 WHERE surveyor = ? AND client_id = ?";
    $stmt_pause_surveyor = $con->prepare($sql_pause_surveyor);
    $stmt_pause_surveyor->bind_param('ii', $surveyor_id, $client_id);

    if ($stmt_pause_surveyor->execute()) {
        // Remove from admin_assignments if pause was selected
        if (removeAdminAssignment($con, $assignment_id)) {
            echo 'success';
        } else {
            echo 'error';
        }
    } else {
        echo 'error';
    }
    $stmt_pause_surveyor->close();
    $con->close();
    return;
}

// If "Remove" is selected, remove all surveyor-client assignments and from admin_assignments
if (isset($_POST['remove_surveyor_client']) && $_POST['remove_surveyor_client'] === 'true') {
    // Remove all surveyor-client assignments
    $sql_remove_surveyor = "DELETE FROM surveyor_assignments WHERE surveyor = ? AND client_id = ?";
    $stmt_remove_surveyor = $con->prepare($sql_remove_surveyor);
    $stmt_remove_surveyor->bind_param('ii', $surveyor_id, $client_id);

    if ($stmt_remove_surveyor->execute()) {
        // Remove from admin_assignments if remove was selected
        if (removeAdminAssignment($con, $assignment_id)) {
            echo 'success';
        } else {
            echo 'error';
        }
    } else {
        echo 'error';
    }
    $stmt_remove_surveyor->close();
    $con->close();
    return;
}

// If neither pause nor remove is selected, just remove from admin_assignments
if (removeAdminAssignment($con, $assignment_id)) {
    echo 'success';
} else {
    echo 'error';
}

$con->close();
?>