<?php
 // super-admin-guard.php
session_start();

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'super_admin') {
    	echo "
        <script>
            alert('ACCESS DENIED. Please re-login.');
            window.location.href = 'sign-in.php';
        </script>
        ";
        exit;
}
?>

<?php
require 'includes/config.php';

$company_id = (int) ($_GET['id'] ?? 0);
if ($company_id <= 0) die("Invalid company");

$conn->begin_transaction();

try {

    // 1️⃣ Delete payments
    $stmt = $conn->prepare("DELETE FROM payments WHERE company_id = ?");
    $stmt->bind_param("i", $company_id);
    $stmt->execute();

    // 2️⃣ Delete subscriptions
    $stmt = $conn->prepare("DELETE FROM subscriptions WHERE company_id = ?");
    $stmt->bind_param("i", $company_id);
    $stmt->execute();

    // 3️⃣ Delete users
    $stmt = $conn->prepare("DELETE FROM users WHERE company_id = ?");
    $stmt->bind_param("i", $company_id);
    $stmt->execute();

    // 4️⃣ Delete company
    $stmt = $conn->prepare("DELETE FROM company WHERE id = ?");
    $stmt->bind_param("i", $company_id);
    $stmt->execute();

    $conn->commit();

    header("Location: master-sub.php?deleted=1");
    exit;

} catch (Throwable $e) {
    $conn->rollback();
    die("Delete failed");
}
