<?php
// ============================================================
// CompanyController  (Front Desk + Admin)
// ============================================================
requireRole(['admin', 'front_desk']);
$db     = Database::getInstance();
$action = $_GET['action'] ?? 'index';

switch ($action) {
    case 'index':
        $search  = sanitize($_GET['q'] ?? '');
        $where   = $search ? "WHERE company_name LIKE :q OR email LIKE :q OR phone LIKE :q" : '';
        $stmt    = $db->prepare("
            SELECT c.*, COUNT(DISTINCT e.equipment_id) AS equip_count,
                   COUNT(DISTINCT cp.contact_id) AS contact_count
            FROM companies c
            LEFT JOIN equipment e ON c.company_id = e.company_id
            LEFT JOIN contact_persons cp ON c.company_id = cp.company_id
            $where
            GROUP BY c.company_id ORDER BY c.company_name
        ");
        $params  = $search ? ['q' => "%$search%"] : [];
        $stmt->execute($params);
        $companies = $stmt->fetchAll();
        include __DIR__ . '/../views/frontdesk/companies_index.php';
        break;

    case 'create':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verifyCsrf();
            $name    = sanitize($_POST['company_name'] ?? '');
            $address = sanitize($_POST['address'] ?? '');
            $phone   = sanitize($_POST['phone'] ?? '');
            $email   = sanitize($_POST['email'] ?? '');
            if (!$name) { setFlash('error', 'Company name required.'); header('Location: ' . APP_URL . '/index.php?page=companies&action=create'); exit; }
            $db->prepare('INSERT INTO companies (company_name, address, phone, email, created_by) VALUES (?,?,?,?,?)')
               ->execute([$name, $address, $phone, $email, $_SESSION['user_id']]);
            $cid = $db->lastInsertId();
            logActivity('create_company', 'companies', "Created: $name", $cid);
            setFlash('success', "Company '$name' created.");
            header('Location: ' . APP_URL . '/index.php?page=companies');
            exit;
        }
        include __DIR__ . '/../views/frontdesk/company_form.php';
        break;

    case 'edit':
        $cid  = (int)($_GET['id'] ?? 0);
        $stmt = $db->prepare('SELECT * FROM companies WHERE company_id = ?');
        $stmt->execute([$cid]);
        $company = $stmt->fetch();
        if (!$company) { setFlash('error', 'Company not found.'); header('Location: ' . APP_URL . '/index.php?page=companies'); exit; }
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verifyCsrf();
            $db->prepare('UPDATE companies SET company_name=?, address=?, phone=?, email=? WHERE company_id=?')
               ->execute([sanitize($_POST['company_name']), sanitize($_POST['address']), sanitize($_POST['phone']), sanitize($_POST['email']), $cid]);
            logActivity('update_company', 'companies', "Updated company ID $cid", $cid);
            setFlash('success', 'Company updated.');
            header('Location: ' . APP_URL . '/index.php?page=companies');
            exit;
        }
        include __DIR__ . '/../views/frontdesk/company_form.php';
        break;

    case 'view':
        $cid     = (int)($_GET['id'] ?? 0);
        $stmt    = $db->prepare('SELECT * FROM companies WHERE company_id = ?');
        $stmt->execute([$cid]);
        $company = $stmt->fetch();
        if (!$company) { setFlash('error', 'Company not found.'); header('Location: ' . APP_URL . '/index.php?page=companies'); exit; }
        $stmt    = $db->prepare('SELECT * FROM contact_persons WHERE company_id = ?');
        $stmt->execute([$cid]); $contacts = $stmt->fetchAll();
        $stmt    = $db->prepare('SELECT * FROM equipment WHERE company_id = ?');
        $stmt->execute([$cid]); $equipments = $stmt->fetchAll();
        include __DIR__ . '/../views/frontdesk/company_view.php';
        break;

    case 'delete':
        $cid = (int)($_GET['id'] ?? 0);
        $db->prepare('DELETE FROM companies WHERE company_id = ?')->execute([$cid]);
        logActivity('delete_company', 'companies', "Deleted company ID $cid", $cid);
        setFlash('success', 'Company deleted.');
        header('Location: ' . APP_URL . '/index.php?page=companies');
        exit;
}
