<?php
/**
 * Agentic Square - Seller Ticket Details & Resolution Console
 * Path: seller/ticket-details.php
 */
require_once __DIR__ . '/../config/config.php';

// SECURITY: Only allow 'seller' role
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'seller') {
    header('Location: ../login.php');
    exit;
}

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

// 1. Fetch Ticket Information and verify ownership
$stmt = $pdo->prepare("SELECT st.*, o.item_name, u.full_name as client_name 
                       FROM support_tickets st 
                       JOIN orders o ON st.order_id = o.id 
                       JOIN users u ON st.user_id = u.id
                       WHERE st.id = ? AND o.seller_id = ?");
$stmt->execute([$ticket_id, $_SESSION['user_id']]);
$t = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$t) { die("Access Denied: Ticket not found or unauthorized."); }

// 2. Handle Replies and Status Toggles
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Toggle Status Logic
    if (isset($_POST['toggle_status'])) {
        $new_status = ($t['ticket_status'] === 'Solved') ? 'Pending' : 'Solved';
        $pdo->prepare("UPDATE support_tickets SET ticket_status = ? WHERE id = ?")->execute([$new_status, $ticket_id]);
    }
    
    // Handle New Reply
    if (isset($_POST['add_reply'])) {
        $msg = filter_var($_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS);
        if (!empty($msg)) {
            $pdo->prepare("INSERT INTO ticket_replies (ticket_id, user_id, message) VALUES (?, ?, ?)")
                ->execute([$ticket_id, $_SESSION['user_id'], $msg]);
        }
    }
    header("Location: ticket-details.php?id=$ticket_id"); exit;
}

// 3. Fetch all replies
$replies = $pdo->prepare("SELECT tr.*, u.full_name FROM ticket_replies tr 
                          JOIN users u ON tr.user_id = u.id 
                          WHERE tr.ticket_id = ? ORDER BY tr.created_at ASC");
$replies->execute([$ticket_id]);
$conversation = $replies->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../sections/header.php';
?>
<body class="bg-nftDark text-white antialiased">
    <?php include_once __DIR__ . '/seller-sidebar.php'; ?>
    <main class="lg:ml-64 p-8 pt-24">
        <div class="max-w-4xl mx-auto space-y-6">
            <div class="bg-slate-900 p-6 rounded-xl border border-slate-800 flex justify-between items-center">
                <div>
                    <h2 class="text-2xl font-bold"><?= htmlspecialchars($t['subject']) ?></h2>
                    <p class="text-nftTextGray text-sm">Client: <?= htmlspecialchars($t['client_name']) ?> | Item: <?= htmlspecialchars($t['item_name']) ?></p>
                </div>
                <form method="POST">
                    <button name="toggle_status" class="px-4 py-2 rounded-lg font-bold text-xs uppercase tracking-wider transition-all <?= $t['ticket_status'] === 'Solved' ? 'bg-amber-600 hover:bg-amber-500' : 'bg-emerald-600 hover:bg-emerald-500' ?>">
                        Mark as <?= $t['ticket_status'] === 'Solved' ? 'Pending' : 'Solved' ?>
                    </button>
                </form>
            </div>

            <div class="bg-slate-800/50 p-6 rounded-xl border border-slate-700">
                <p class="text-xs font-bold text-nftAccentCyan uppercase tracking-widest">Client Original Request:</p>
                <p class="mt-3 text-slate-200"><?= nl2br(htmlspecialchars($t['message'])) ?></p>
            </div>

            <?php foreach ($conversation as $r): ?>
            <div class="bg-slate-900 p-4 rounded-xl border border-slate-800 ml-8">
                <p class="text-[10px] font-bold text-nftTextGray uppercase"><?= htmlspecialchars($r['full_name']) ?> replied:</p>
                <p class="mt-1 text-sm"><?= nl2br(htmlspecialchars($r['message'])) ?></p>
            </div>
            <?php endforeach; ?>

            <form method="POST" class="bg-slate-900 p-6 rounded-xl border border-slate-800 space-y-4">
                <textarea name="message" class="w-full bg-slate-950 p-4 rounded border border-slate-700 focus:border-nftAccentCyan outline-none" placeholder="Type your response to the client..." required></textarea>
                <button name="add_reply" class="bg-nftAccentCyan px-6 py-2 rounded text-black font-bold text-sm">Send Reply</button>
            </form>
        </div>
    </main>
</body>