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

function updateAssignmentColumnExists(mysqli $con, string $column): bool
{
    $stmt = $con->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'admin_assignments' AND COLUMN_NAME = ? LIMIT 1");
    if (!$stmt) return false;
    $stmt->bind_param('s', $column);
    $stmt->execute();
    $stmt->store_result();
    $exists = $stmt->num_rows > 0;
    $stmt->close();
    return $exists;
}

$hasUpdatedAt = updateAssignmentColumnExists($con, 'updated_at');
$hasDiaryColumns = updateAssignmentColumnExists($con, 'start_time')
    && updateAssignmentColumnExists($con, 'end_time')
    && updateAssignmentColumnExists($con, 'notes')
    && updateAssignmentColumnExists($con, 'location_id')
    && updateAssignmentColumnExists($con, 'asset_id');

if (!$hasDiaryColumns) {
    echo 'error: Diary columns are not available for this tenant.';
    exit;
}

$assignment_id = (int)($_POST['assignment_id'] ?? 0);
$client_id = (int)($_POST['client_id'] ?? 0);
$surveyor_id = (int)($_POST['surveyor_id'] ?? 0);
$appointment_date = (int)($_POST['appointment_date'] ?? 0);
$start_time = !empty($_POST['start_time']) ? (int)$_POST['start_time'] : null;
$end_time = !empty($_POST['end_time']) ? (int)$_POST['end_time'] : null;
$location_id = !empty($_POST['location_id']) ? (int)$_POST['location_id'] : null;
$asset_id = !empty($_POST['asset_id']) ? (int)$_POST['asset_id'] : null;
$notes = trim((string)($_POST['notes'] ?? ''));
$status = isset($_POST['status']) ? (int)$_POST['status'] : 0;

if ($assignment_id <= 0 || $client_id <= 0 || $surveyor_id <= 0 || $appointment_date <= 0) {
    echo 'error: Missing assignment details.';
    exit;
}

if ($start_time !== null && $end_time !== null && $end_time <= $start_time) {
    echo 'error: End time must be after start time.';
    exit;
}

if ($start_time !== null && $end_time !== null) {
    $stmt = $con->prepare("
        SELECT id
        FROM admin_assignments
        WHERE surveyor_id = ?
          AND id <> ?
          AND status IN (0, 1)
          AND start_time IS NOT NULL
          AND end_time IS NOT NULL
          AND start_time < ?
          AND end_time > ?
        LIMIT 1
    ");
    $stmt->bind_param('iiii', $surveyor_id, $assignment_id, $end_time, $start_time);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) {
        echo 'error: Appointment overlaps with another job for this surveyor.';
        $stmt->close();
        exit;
    }
    $stmt->close();
}

$startSql = $start_time !== null ? (string)$start_time : "NULL";
$endSql = $end_time !== null ? (string)$end_time : "NULL";
$locationSql = $location_id !== null ? (string)$location_id : "NULL";
$assetSql = $asset_id !== null ? (string)$asset_id : "NULL";
$notesSql = "'" . $con->real_escape_string($notes) . "'";
$updatedClause = $hasUpdatedAt ? ", updated_at = UNIX_TIMESTAMP()" : "";

$stmt = $con->prepare("
    UPDATE admin_assignments
    SET client_id = ?,
        surveyor_id = ?,
        appointment_date = ?,
        start_time = {$startSql},
        end_time = {$endSql},
        notes = {$notesSql},
        location_id = {$locationSql},
        asset_id = {$assetSql},
        status = ?
        {$updatedClause}
    WHERE id = ?
");
$stmt->bind_param('iiiii', $client_id, $surveyor_id, $appointment_date, $status, $assignment_id);

echo $stmt->execute() ? 'success' : 'error: ' . $stmt->error;

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