<?php
include_once('../header.php');  // assumes this starts session & sets $link

// 1) ensure the user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: " . WEB_URL . "logout.php");
    exit;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // 2) sanitize the incoming ID
    $assignment_id = (int) $_POST['assignment_id'];

    // 3) fix the date format: four-digit year, space-separated
    $current_time = date("Y-m-d H:i:s");

    // 4) first, mark the old assignment
    $sql1 = "
      UPDATE tenant_unit
         SET past_assignment = 1,
             last_action_by   = {$_SESSION['user_id']}
       WHERE id = {$assignment_id}
    ";
    if (!mysqli_query($link, $sql1)) {
        error_log("eject_tenant.php SQL error (past_assignment): " . mysqli_error($link));
        $_SESSION["message"] = "Unable to mark past assignment";
    } else {
        // 5) then, record the removal time
        $sql2 = "
          UPDATE tenant_unit
             SET date_removed = '{$current_time}'
           WHERE id = {$assignment_id}
        ";
        if (mysqli_query($link, $sql2)) {
            $_SESSION["message"] = "Tenant Ejected Successfully";
        } else {
            error_log("eject_tenant.php SQL error (date_removed): " . mysqli_error($link));
            $_SESSION["message"] = "Unable to eject tenant";
        }
    }

    // 6) close the connection & redirect
    mysqli_close($link);
} else {
    $_SESSION["message"] = "Invalid Request";
}

header("Location: " . WEB_URL . "tenant/tenantlist.php");
exit;
