<?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.");
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    die("Invalid company ID.");
}

try {
    // Optional: check if company exists
    $check = $db->prepare("SELECT id FROM companies WHERE id = :id LIMIT 1");
    $check->bindValue(':id', $id, PDO::PARAM_INT);
    $check->execute();

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

    // 🔥 IMPORTANT: delete related users first (if using foreign keys)
    $deleteMembers = $db->prepare("
        DELETE FROM company_users
        WHERE company_id = :company_id
    ");
    $deleteMembers->bindValue(':company_id', $id, PDO::PARAM_INT);
    $deleteMembers->execute();

    // Then delete company
    $deleteCompany = $db->prepare("
        DELETE FROM companies
        WHERE id = :id
    ");
    $deleteCompany->bindValue(':id', $id, PDO::PARAM_INT);
    $deleteCompany->execute();

    header("Location: /dms/companies.php?deleted=1");
    exit;

} catch (PDOException $e) {
    die("Delete failed: " . $e->getMessage());
}