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

$assignment_id = $_POST['assignment_id'];
$action = $_POST['action'];  // 'started' or 'completed'

// Get the surveyor's name and client name from the assignment
$sql = "
    SELECT s.forename, s.surname, cd.clientname 
    FROM admin_assignments aa
    LEFT JOIN surveyor s ON aa.surveyor_id = s.id
    LEFT JOIN clientdetails cd ON aa.client_id = cd.clientnumber
    WHERE aa.id = ?
";
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $assignment_id);
$stmt->execute();
$result = $stmt->get_result();
$assignment = $result->fetch_assoc();

$surveyor_name = $assignment['forename'] . ' ' . $assignment['surname'];
$client_name = $assignment['clientname'];

// Get current UK date and time
$timezone = new DateTimeZone('Europe/London');
$date = new DateTime('now', $timezone);
$formattedDate = $date->format('d/m/Y H:i:s');  // e.g., 25/09/2024 15:30:45

// Construct the message
$message = '';
if ($action === 'started') {
    $message = "Surveyor $surveyor_name has started the assignment at $client_name on $formattedDate .";
} elseif ($action === 'completed') {
    $message = "Surveyor $surveyor_name has completed the assignment at $client_name on $formattedDate .";
}

// Insert the notification for all admins
$sql = "INSERT INTO messages (assignment_id, sender_type, recipient_id, message, status, sent_at) 
        VALUES (?, 'surveyor', 0, ?, 'normal', UNIX_TIMESTAMP())";
$stmt = $con->prepare($sql);
$stmt->bind_param('is', $assignment_id, $message);

if ($stmt->execute()) {
    echo 'success';
} else {
    echo 'error';
}

$stmt->close();
$con->close();
?>