<?php
require_once __DIR__ . '/../../../includes/auth.php';
requireLogin();

require_once __DIR__ . '/../../../config/database.php';

$company_id = $_SESSION['company_id'];

$ticket_id = isset($_POST['ticket_id']) ? (int)$_POST['ticket_id'] : 0;
$user_id   = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;

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

/* =============================
   PREVENT DUPLICATES
============================= */

$check = $pdo->prepare("
    SELECT id 
    FROM ticket_watchers 
    WHERE ticket_id = ? AND user_id = ? AND company_id = ?
");
$check->execute([$ticket_id, $user_id, $company_id]);

if (!$check->fetch()) {

    $stmt = $pdo->prepare("
        INSERT INTO ticket_watchers (ticket_id, user_id, company_id)
        VALUES (?, ?, ?)
    ");
    $stmt->execute([$ticket_id, $user_id, $company_id]);
}

/* =============================
   REDIRECT BACK
============================= */

header("Location: view.php?id=" . $ticket_id);
exit;