<?php
session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') === 'guest') {
    header("Location: login.php");
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$user_id = (int) ($_SESSION['user_id'] ?? 0);

/*
|--------------------------------------------------------------------------
| Workspace logic
|--------------------------------------------------------------------------
*/
$workspace_type = $_SESSION['workspace_type'] ?? 'personal';
$active_company_id = isset($_SESSION['active_company_id']) && $_SESSION['active_company_id'] !== ''
    ? (int) $_SESSION['active_company_id']
    : null;

$is_company_workspace = ($workspace_type === 'company' && $active_company_id !== null);

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid car ID.");
}

$id = (int) $_GET['id'];

function bindOwnership(PDOStatement $stmt, bool $is_company_workspace, ?int $active_company_id, int $user_id): void
{
    if ($is_company_workspace) {
        $stmt->bindValue(":company_id", $active_company_id, PDO::PARAM_INT);
    } else {
        $stmt->bindValue(":user_id", $user_id, PDO::PARAM_INT);
    }
}

if ($is_company_workspace) {
    $ownershipSql = "id = :id AND company_id = :company_id";
} else {
    $ownershipSql = "id = :id AND user_id = :user_id AND company_id IS NULL";
}

$stmt = $db->prepare("
    SELECT *
    FROM cars
    WHERE {$ownershipSql}
    LIMIT 1
");
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
bindOwnership($stmt, $is_company_workspace, $active_company_id, $user_id);
$stmt->execute();
$car = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$car) {
    die("Car not found.");
}

$delete = $db->prepare("
    DELETE FROM cars
    WHERE {$ownershipSql}
");
$delete->bindValue(":id", $id, PDO::PARAM_INT);
bindOwnership($delete, $is_company_workspace, $active_company_id, $user_id);
$delete->execute();

header("Location: my_cars.php");
exit;
?>