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

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

$company_id = $_SESSION['company_id'];
$user_id    = $_SESSION['user_id'];

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

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

/* =============================
   LOAD TICKET
============================= */

$stmt = $pdo->prepare("
    SELECT t.*, u.full_name AS assigned_name
    FROM operations_tickets t
    LEFT JOIN users u ON u.id = t.assigned_to
    WHERE t.id = ? AND t.company_id = ?
    LIMIT 1
");
$stmt->execute([$id, $company_id]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC);

/* =============================
   LOAD WATCHERS
============================= */

$watchStmt = $pdo->prepare("
    SELECT tw.id, tw.user_id, u.full_name
    FROM ticket_watchers tw
    LEFT JOIN users u ON u.id = tw.user_id
    WHERE tw.ticket_id = ? AND tw.company_id = ?
");
$watchStmt->execute([$id, $company_id]);

$watchersList = $watchStmt->fetchAll(PDO::FETCH_ASSOC);

if (!$ticket) {
    header("Location: index.php");
    exit;
}

/* =============================
   STATUS BADGE
============================= */

$statusClass = 'badge-muted';

switch ($ticket['status']) {
    case 'Open':
    case 'Assigned':
    case 'Awaiting Customer':
        $statusClass = 'badge-warning';
        break;
    case 'In Progress':
    case 'Resolved':
        $statusClass = 'badge-success';
        break;
    case 'Escalated':
        $statusClass = 'badge-danger';
        break;
    case 'Closed':
        $statusClass = 'badge-muted';
        break;
}

/* =============================
   SLA CHECK
============================= */

$isOverdue = false;
if (!empty($ticket['due_at'])) {
    if (
        strtotime($ticket['due_at']) < time() &&
        !in_array($ticket['status'], ['Resolved','Closed'])
    ) {
        $isOverdue = true;
    }
}

/* =============================
   HANDLE COMMENT SUBMIT
============================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['comment'])) {

    $comment = trim($_POST['comment']);

    if ($comment !== '') {

        // SAVE COMMENT
        $stmt = $pdo->prepare("
            INSERT INTO operations_ticket_comments
            (ticket_id, comment, created_by, created_at)
            VALUES (?, ?, ?, NOW())
        ");
        $stmt->execute([$id, $comment, $user_id]);

        /* =============================
           ðŸ”” CREATE NOTIFICATION
        ============================== */

        $notifStmt = $pdo->prepare("
            INSERT INTO notifications
            (company_id, user_id, title, message, link, created_at)
            VALUES (?, ?, ?, ?, ?, NOW())
        ");

        $notifTitle = "New Comment on Ticket";
        $notifMessage = substr($comment, 0, 120);
        $notifLink = "/core/public/operations/tickets/view.php?id=" . $id;

        $notifRecipients = [];

// Assigned user
if (!empty($ticket['assigned_to'])) {
    $notifRecipients[] = $ticket['assigned_to'];
}

// Creator
if (!empty($ticket['created_by'])) {
    $notifRecipients[] = $ticket['created_by'];
}

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

$watchers = $watchStmt->fetchAll(PDO::FETCH_COLUMN);

foreach ($watchers as $wid) {
    $notifRecipients[] = $wid;
}

// Clean list
$notifRecipients = array_unique($notifRecipients);
$notifRecipients = array_filter($notifRecipients, function($uid) use ($user_id) {
    return $uid != $user_id;
});

// Insert notifications
foreach ($notifRecipients as $uid) {
    $notifStmt->execute([
        $company_id,
        $uid,
        $notifTitle,
        $notifMessage,
        $notifLink
    ]);
}
        
       require_once __DIR__ . '/../../../includes/mailer.php';

/* =============================
   SEND COMMENT EMAILS (CLEAN)
============================= */

function sendCommentEmail($pdo, $userId, $ticket, $comment, $id){

    $u = $pdo->prepare("
        SELECT email, full_name 
        FROM users 
        WHERE id = ?
    ");
    $u->execute([$userId]);
    $user = $u->fetch(PDO::FETCH_ASSOC);

    if (!$user || empty($user['email'])) return;

    $emailBody = "
    <div style='font-family:Poppins,Arial,sans-serif;background:#f4f6f8;padding:20px;'>

        <div style='max-width:600px;margin:auto;background:#ffffff;border-radius:12px;overflow:hidden;'>

            <div style='background:#f2531e;color:#fff;padding:15px;font-size:16px;font-weight:bold;'>
                InfraCore™ Notification
            </div>

            <div style='padding:20px;'>

                <p>Hello <strong>{$user['full_name']}</strong>,</p>

                <p>A new comment was added:</p>

                <div style='padding:12px;background:#f9fafb;border-left:4px solid #f2531e;margin:15px 0;'>
                    <strong>{$ticket['ticket_number']}</strong><br>
                    {$comment}
                </div>

                <a href='https://crm.edmsolutions.co.za/core/public/operations/tickets/view.php?id={$id}'
                   style='background:#f2531e;color:#fff;padding:10px 15px;text-decoration:none;border-radius:6px;'>
                   View Ticket
                </a>

            </div>

        </div>

    </div>
    ";

    sendEmail(
        $user['email'],
        "Update on Ticket - {$ticket['ticket_number']}",
        $emailBody
    );
}


/* =============================
   BUILD RECIPIENT LIST
============================= */

$recipients = [];

// Assigned user
if (!empty($ticket['assigned_to'])) {
    $recipients[] = $ticket['assigned_to'];
}

// Ticket creator
if (!empty($ticket['created_by'])) {
    $recipients[] = $ticket['created_by'];
}


/* =============================
   ADD WATCHERS (NEW)
============================= */

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

$watchers = $watchStmt->fetchAll(PDO::FETCH_COLUMN);

foreach ($watchers as $wid) {
    $recipients[] = $wid;
}

// Remove duplicates
$recipients = array_unique($recipients);

// Remove the current user (person who commented)
$recipients = array_filter($recipients, function($uid) use ($user_id) {
    return $uid != $user_id;
});

/* =============================
   SEND EMAILS
============================= */

foreach ($recipients as $uid) {
    sendCommentEmail($pdo, $uid, $ticket, $comment, $id);
}

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

/* =============================
   LOAD TIMELINE
============================= */

$timeline = [];

/* EVENTS */
$evtStmt = $pdo->prepare("
    SELECT 'EVENT' AS type,
           e.event_type AS title,
           e.message AS content,
           e.created_at,
           u.full_name
    FROM operations_ticket_events e
    LEFT JOIN users u ON u.id = e.created_by
    WHERE e.ticket_id = ?
");
$evtStmt->execute([$id]);
$timeline = array_merge($timeline, $evtStmt->fetchAll(PDO::FETCH_ASSOC));

/* COMMENTS */
$cStmt = $pdo->prepare("
    SELECT 'COMMENT' AS type,
           c.comment AS title,
           c.comment AS content,
           c.created_at,
           u.full_name
    FROM operations_ticket_comments c
    LEFT JOIN users u ON u.id = c.created_by
    WHERE c.ticket_id = ?
");
$cStmt->execute([$id]);
$timeline = array_merge($timeline, $cStmt->fetchAll(PDO::FETCH_ASSOC));

usort($timeline, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

$lastActivity = $timeline[0]['created_at'] ?? null;

/* LOAD LAYOUT */
require_once __DIR__ . '/../../../includes/layout.php';
?>

<div class="page-header">
    <h2>Ticket: <?= htmlspecialchars($ticket['ticket_number']) ?></h2>
    <p class="page-subtitle"><?= htmlspecialchars($ticket['subject'] ?? '') ?></p>
</div>

<div style="max-width:1000px;">

<div class="card-form" style="max-width:100%;">

<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:18px;">

<div>
<strong>Status</strong><br>
<span class="badge <?= $statusClass ?>">
<?= htmlspecialchars($ticket['status']) ?>
</span>

<?php if ($ticket['category'] === 'Performance / PIP'): ?>
<div style="
    margin-top:10px;
    padding:14px;
    border-radius:12px;
    background:#fff4e5;
    border-left:4px solid #f2531e;
">

    <div style="font-weight:600; margin-bottom:6px;">
        âš  Performance Improvement Plan
    </div>

    <div style="font-size:13px; line-height:1.6;">

        <strong>Stage:</strong> 
        <?= htmlspecialchars($ticket['pip_stage'] ?? 'Active') ?><br>

        <strong>Start Date:</strong> 
        <?= !empty($ticket['pip_start_date']) 
            ? date('Y-m-d', strtotime($ticket['pip_start_date'])) 
            : 'N/A' ?><br>

        <strong>Review Date:</strong> 
        <?= !empty($ticket['pip_review_date']) 
            ? date('Y-m-d', strtotime($ticket['pip_review_date'])) 
            : 'N/A' ?><br>

        <strong>End Date:</strong> 
        <?= !empty($ticket['pip_end_date']) 
            ? date('Y-m-d', strtotime($ticket['pip_end_date'])) 
            : 'N/A' ?>

    </div>
</div>
<?php endif; ?>
</div>

<!-- ADD COMMENT -->

<div style="background:#fff;padding:20px;border-radius:12px;margin-top:20px;">
<h4>Add Comment</h4>

<form method="POST">
<textarea name="comment" required
    style="width:100%;padding:10px;border:1px solid #ddd;border-radius:8px;"
    rows="4"
    placeholder="Write a comment..."></textarea>

<button class="btn btn-primary" style="margin-top:10px;">
    Add Comment
</button>
</form>

</div>

<div>
<strong>Priority</strong><br>
<span class="badge badge-danger">
<?= htmlspecialchars($ticket['priority']) ?>
</span>
</div>

<div>
<strong>Assigned To</strong><br>
<?= $ticket['assigned_name']
? htmlspecialchars($ticket['assigned_name'])
: '<span class="badge badge-muted">Unassigned</span>' ?>
</div>


<div style="margin-top:15px;">
<strong>Add Watcher</strong>

<form method="POST" action="add_watcher.php" style="display:flex;gap:10px;margin-top:5px;">
    <input type="hidden" name="ticket_id" value="<?= $ticket['id'] ?>">

    <select name="user_id" required style="padding:8px;border-radius:6px;">
        <option value="">Select user</option>

        <?php
        $users = $pdo->prepare("SELECT id, full_name FROM users WHERE company_id = ?");
        $users->execute([$company_id]);

        foreach ($users as $u):
        ?>
            <option value="<?= $u['id'] ?>">
                <?= htmlspecialchars($u['full_name']) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <button class="btn btn-primary">Add</button>
</form>
</div>

<!-- =============================
     WATCHERS LIST
============================= -->

<?php if (!empty($watchersList)): ?>
<div style="margin-top:15px;">
    <strong>Watchers</strong>

    <div style="margin-top:8px; display:flex; flex-wrap:wrap; gap:8px;">

        <?php foreach ($watchersList as $w): ?>

            <div style="
                display:flex;
                align-items:center;
                gap:6px;
                background:#f3f4f6;
                padding:6px 10px;
                border-radius:20px;
                font-size:13px;
            ">

                <?= htmlspecialchars($w['full_name'] ?? 'User') ?>

                <!-- REMOVE BUTTON -->
                <form method="POST" action="remove_watcher.php" style="margin:0;">
                    <input type="hidden" name="watcher_id" value="<?= $w['id'] ?>">
                    <input type="hidden" name="ticket_id" value="<?= $ticket['id'] ?>">

                    <button type="submit" style="
                        border:none;
                        background:none;
                        color:#dc2626;
                        font-weight:bold;
                        cursor:pointer;
                    ">
                        ×
                    </button>
                </form>

            </div>

        <?php endforeach; ?>

    </div>
</div>
<?php endif; ?>

<div>
<strong>SLA Due</strong><br>

<?php if ($ticket['due_at']): ?>
<div id="sla-timer"
     data-due="<?= htmlspecialchars($ticket['due_at']) ?>"
     style="font-weight:600;">
Loading SLA...
</div>
<?php else: ?>
<span class="badge badge-muted">No SLA</span>
<?php endif; ?>
</div>

<div>
<strong>Created</strong><br>
<?= date('Y-m-d H:i', strtotime($ticket['created_at'])) ?>
</div>

<div>
<strong>Last Activity</strong><br>
<?= $lastActivity
? date('Y-m-d H:i', strtotime($lastActivity))
: '<span class="badge badge-muted">No activity</span>' ?>
</div>

</div>

<hr style="margin:20px 0;">

<strong>Description</strong><br><br>
<?= nl2br(htmlspecialchars($ticket['description'])) ?>

<div style="margin-top:20px; display:flex; gap:10px; flex-wrap:wrap;">
<a href="update.php?id=<?= $ticket['id'] ?>" class="btn btn-primary">
Update Ticket
</a>
<a href="index.php" class="btn btn-light">
Back to Queue
</a>
</div>

</div>

<!-- TIMELINE -->

<div style="background:#fff;padding:20px;border-radius:12px;margin-top:25px;box-shadow:0 4px 14px rgba(0,0,0,0.05);">
<h4>Activity Timeline</h4>

<?php if (empty($timeline)): ?>
<div class="badge badge-muted">No activity yet.</div>
<?php else: ?>

<div style="margin-top:15px;border-left:3px solid var(--edm-orange);padding-left:20px;">

<?php foreach ($timeline as $item): ?>

<?php
$badgeClass = 'badge-warning';

if ($item['type'] === 'COMMENT') {
    $badgeClass = 'badge-success';
}

if (stripos($item['title'], 'PIP') !== false) {
    $badgeClass = 'badge-danger';
}
?>

<div style="margin-bottom:22px;">
<div style="font-size:13px;color:#6b7280;">
<?= date('Y-m-d H:i', strtotime($item['created_at'])) ?>
â€¢ <?= htmlspecialchars($item['full_name'] ?? 'System') ?>
</div>

<div style="margin-top:6px;">
<span class="badge <?= $badgeClass ?>">
<?= htmlspecialchars($item['title']) ?>
</span>
</div>

<div style="margin-top:6px;">
<?= nl2br(htmlspecialchars($item['content'])) ?>
</div>
</div>

<?php endforeach; ?>

</div>
<?php endif; ?>
</div>

</div>

<script>
document.addEventListener("DOMContentLoaded", function(){

const el = document.getElementById("sla-timer");
if (!el) return;

const dueDate = new Date(el.dataset.due.replace(' ', 'T')).getTime();

function updateTimer(){
const now = new Date().getTime();
let diff = dueDate - now;

const overdue = diff < 0;
diff = Math.abs(diff);

const hours = Math.floor(diff / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

if (overdue) {
el.innerText = "OVERDUE by " + hours + "h " + minutes + "m";
el.style.color = "#dc2626";
} else {
el.innerText = hours + "h " + minutes + "m remaining";
el.style.color = hours <= 4 ? "#f59e0b" : "#16a34a";
}
}

updateTimer();
setInterval(updateTimer, 60000);

});
</script>
<?php
require_once __DIR__ . '/../../../includes/helper.php';
renderHelper('view');
require_once __DIR__ . '/../../../includes/layout_footer.php'; ?>