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

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

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

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

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

if ($company_id <= 0 || $user_id <= 0) {
    die("Invalid company ID or user ID.");
}

try {
    $check = $db->prepare("
        SELECT id
        FROM company_users
        WHERE company_id = :company_id
          AND user_id = :user_id
        LIMIT 1
    ");
    $check->bindValue(':company_id', $company_id, PDO::PARAM_INT);
    $check->bindValue(':user_id', $user_id, PDO::PARAM_INT);
    $check->execute();

    if (!$check->fetch(PDO::FETCH_ASSOC)) {
        die("Company user not found.");
    }

    $delete = $db->prepare("
        DELETE FROM company_users
        WHERE company_id = :company_id
          AND user_id = :user_id
    ");
    $delete->bindValue(':company_id', $company_id, PDO::PARAM_INT);
    $delete->bindValue(':user_id', $user_id, PDO::PARAM_INT);
    $delete->execute();

    header("Location: /dms/add_user_to_company.php?company_id=" . $company_id . "&deleted=1");
    exit;
} catch (PDOException $e) {
    die("Delete failed: " . $e->getMessage());
}