<?php
/**
 * Agentic Square - Ticket Timeline View & Resolution Console
 * Path: client/ticket-details.php
 */

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

// SECURITY ACCESS GUARD: Only allow standard 'user' role
if (!isset($_SESSION['user_id'])) { header('Location: ../login.php'); exit; }

$ticket_id = filter_var($_GET['id'] ?? 0, FILTER_VALIDATE_INT);

if (!$ticket_id) {
    header('Location: support-tickets.php');
    exit;
}

// Handle ticket processing interaction forms
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['mark_solved'])) {
        $update = $pdo->prepare("UPDATE support_tickets SET ticket_status = 'Solved' WHERE id = ? AND user_id = ?");
        $update->execute([$ticket_id, $_SESSION['user_id']]);
    }

    if (isset($_POST['add_reply'])) {
        $reply_msg = filter_var(trim($_POST['reply_message'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
        if (!empty($reply_msg)) {
            $insert = $pdo->prepare("INSERT INTO ticket_replies (ticket_id, user_id, message) VALUES (?, ?, ?)");
            $insert->execute([$ticket_id, $_SESSION['user_id'], $reply_msg]);
        }
    }
    
    header("Location: ticket-details.php?id=" . $ticket_id);
    exit;
}

// Fetch core data values combined with target order attributes
$ticketQuery = "SELECT st.*, o.item_name 
                FROM support_tickets st 
                LEFT JOIN orders o ON st.order_id = o.id 
                WHERE st.id = ? AND st.user_id = ? LIMIT 1";
$ticketStmt = $pdo->prepare($ticketQuery);
$ticketStmt->execute([$ticket_id, $_SESSION['user_id']]);
$t = $ticketStmt->fetch(PDO::FETCH_ASSOC);

if (!$t) {
    header('Location: support-tickets.php');
    exit;
}

// Pull historical communication node timeline sequences
$repliesStmt = $pdo->prepare("SELECT tr.*, u.full_name, u.role 
                              FROM ticket_replies tr 
                              INNER JOIN users u ON tr.user_id = u.id 
                              WHERE tr.ticket_id = ? 
                              ORDER BY tr.created_at ASC");
$repliesStmt->execute([$ticket_id]);
$replies = $repliesStmt->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">
    <?php include_once __DIR__ . '/client-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-16 px-4 sm:px-6 lg:px-8">
        <div class="max-w-4xl mx-auto space-y-6">
            
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between border-b border-slate-900/60 pb-6 gap-4">
                <div>
                    <span class="text-xs font-bold tracking-widest text-nftAccentPurple uppercase block mb-1">Inquiry Matrix Reference #<?= $t['id'] ?></span>
                    <h1 class="text-2xl font-extrabold text-white"><?= htmlspecialchars($t['subject']) ?></h1>
                    <p class="text-xs text-nftTextGray mt-1">Associated Pipeline: <span class="text-white font-semibold"><?= htmlspecialchars($t['item_name'] ?? 'N/A') ?></span></p>
                </div>
                <div class="flex items-center gap-3">
                    <span class="px-3 py-1.5 rounded-lg text-xs font-bold uppercase tracking-wider <?= $t['ticket_status'] === 'Solved' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-amber-500/10 text-amber-400 border border-amber-500/20' ?>">
                        <?= $t['ticket_status'] ?>
                    </span>
                    <?php if ($t['ticket_status'] !== 'Solved'): ?>
                        <form method="POST">
                            <button type="submit" name="mark_solved" class="px-4 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-500 transition-all text-xs font-bold uppercase tracking-wider text-white">
                                Mark Solved
                            </button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>

            <div class="glass-card p-6 rounded-2xl border border-slate-800/80 bg-slate-900/10 space-y-4">
                <div class="flex justify-between items-center text-xs text-nftTextGray border-b border-slate-900 pb-3">
                    <span class="font-bold uppercase text-nftAccentCyan">Origin Message Entry</span>
                    <span class="font-mono"><?= date('M d, Y H:i', strtotime($t['created_at'])) ?></span>
                </div>
                <p class="text-sm text-slate-200 leading-relaxed font-sans"><?= nl2br(htmlspecialchars($t['message'])) ?></p>
            </div>

            <?php if (!empty($replies)): ?>
                <div class="space-y-4 pt-4">
                    <h3 class="text-xs font-bold text-nftTextGray uppercase tracking-widest">// Communication Stream Log</h3>
                    <?php foreach ($replies as $r): ?>
                        <?php $isSelf = ((int)$r['user_id'] === (int)$_SESSION['user_id']); ?>
                        <div class="glass-card p-5 rounded-2xl border <?= $isSelf ? 'border-slate-800 bg-slate-950/10' : 'border-nftAccentPurple/20 bg-nftAccentPurple/5' ?> space-y-3">
                            <div class="flex justify-between items-center text-xs">
                                <span class="font-bold <?= $isSelf ? 'text-slate-300' : 'text-nftAccentPurple' ?>">
                                    <?= htmlspecialchars($r['full_name']) ?> 
                                    <span class="text-[10px] uppercase font-mono tracking-widest text-nftTextGray ml-1">(<?= $r['role'] ?>)</span>
                                </span>
                                <span class="font-mono text-nftTextGray"><?= date('M d, Y H:i', strtotime($r['created_at'])) ?></span>
                            </div>
                            <p class="text-sm text-slate-300 leading-relaxed font-sans"><?= nl2br(htmlspecialchars($r['message'])) ?></p>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if ($t['ticket_status'] !== 'Solved'): ?>
                <form method="POST" class="pt-6 space-y-4">
                    <div class="space-y-2">
                        <label class="text-xs font-bold uppercase text-nftTextGray">Write Response Entry</label>
                        <textarea name="reply_message" rows="4" required placeholder="Type instructions or structural processing comments..." class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentPurple rounded-xl p-4 text-sm text-white focus:outline-none transition-all resize-none"></textarea>
                    </div>
                    <div class="flex justify-end">
                        <button type="submit" name="add_reply" class="px-6 py-3 rounded-xl bg-gradient-to-r from-nftAccentPurple to-nftAccentCyan font-bold text-xs uppercase tracking-widest text-white hover:opacity-90 transition-all">
                            Post Response Matrix
                        </button>
                    </div>
                </form>
            <?php else: ?>
                <div class="p-4 bg-emerald-500/5 border border-emerald-500/10 rounded-xl text-center text-xs font-mono text-emerald-400">
                    This inquiry path state sequence is flagged as finalized and locked. No further data writes allowed.
                </div>
            <?php endif; ?>

        </div>
    </main>
</body>
</html>