<?php
// ContactController
requireRole(['admin', 'front_desk']);
$db     = Database::getInstance();
$action = $_GET['action'] ?? 'create';
$cid    = (int)($_GET['company_id'] ?? 0);

if ($action === 'create') {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        verifyCsrf();
        $cid = (int)($_POST['company_id'] ?? 0);
        $db->prepare('INSERT INTO contact_persons (company_id, contact_name, phone_number, email, position) VALUES (?,?,?,?,?)')
           ->execute([$cid, sanitize($_POST['contact_name']), sanitize($_POST['phone_number']), sanitize($_POST['email']), sanitize($_POST['position'])]);
        logActivity('create_contact', 'contacts', "Added contact for company $cid");
        setFlash('success', 'Contact person added.');
        header('Location: ' . APP_URL . '/index.php?page=companies&action=view&id=' . $cid);
        exit;
    }
    $companies = $db->query('SELECT company_id, company_name FROM companies ORDER BY company_name')->fetchAll();
    include __DIR__ . '/../views/frontdesk/contact_form.php';
} elseif ($action === 'delete') {
    $contactId = (int)($_GET['id'] ?? 0);
    $stmt = $db->prepare('SELECT company_id FROM contact_persons WHERE contact_id = ?');
    $stmt->execute([$contactId]); $row = $stmt->fetch();
    $db->prepare('DELETE FROM contact_persons WHERE contact_id = ?')->execute([$contactId]);
    logActivity('delete_contact', 'contacts', "Deleted contact $contactId");
    setFlash('success', 'Contact deleted.');
    header('Location: ' . APP_URL . '/index.php?page=companies&action=view&id=' . ($row['company_id'] ?? 0));
    exit;
}
