<?php
require_once '../../includes/auth.php';
require_once '../../db.php';

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

if ($id <= 0) {
    header("Location: index.php");
    exit;
}

// Verify company exists
$co = $conn->query("SELECT * FROM company_master WHERE id = $id LIMIT 1")->fetch_assoc();
if (!$co) {
    header("Location: index.php?error=" . urlencode("Company not found."));
    exit;
}

// Do not allow deleting the default company
if ($co['is_default']) {
    header("Location: index.php?error=" . urlencode("Cannot delete the default company. Please set another company as default first."));
    exit;
}

// Check for sales_invoices referencing this company
$checkSales = $conn->query("SHOW TABLES LIKE 'sales_invoices'");
if ($checkSales && $checkSales->num_rows > 0) {
    // Check if company_id column exists on sales_invoices
    $cols = $conn->query("SHOW COLUMNS FROM sales_invoices LIKE 'company_id'");
    if ($cols && $cols->num_rows > 0) {
        $cnt = $conn->query("SELECT COUNT(*) FROM sales_invoices WHERE company_id = $id")->fetch_row()[0] ?? 0;
        if ($cnt > 0) {
            header("Location: index.php?error=" . urlencode("Cannot delete: this company has $cnt sales invoice(s) linked to it."));
            exit;
        }
    }
}

// Check for purchase_orders referencing this company
$checkPO = $conn->query("SHOW TABLES LIKE 'purchase_orders'");
if ($checkPO && $checkPO->num_rows > 0) {
    $cols = $conn->query("SHOW COLUMNS FROM purchase_orders LIKE 'company_id'");
    if ($cols && $cols->num_rows > 0) {
        $cnt = $conn->query("SELECT COUNT(*) FROM purchase_orders WHERE company_id = $id")->fetch_row()[0] ?? 0;
        if ($cnt > 0) {
            header("Location: index.php?error=" . urlencode("Cannot delete: this company has $cnt purchase order(s) linked to it."));
            exit;
        }
    }
}

// Delete associated bank accounts first
$conn->query("DELETE FROM company_bank_accounts WHERE company_id = $id");

// Delete user_companies associations
$conn->query("DELETE FROM user_companies WHERE company_id = $id");

// Delete the company
$conn->query("DELETE FROM company_master WHERE id = $id");

// If this was the active company in any session, those sessions will self-correct via auth.php

header("Location: index.php?deleted=1");
exit;
