<?php
session_start();
require 'config/db.php';
include 'includes/header.php';

if (!isset($_SESSION['user_id']) || !isset($_GET['id'])) {
    header("Location: login.php"); exit();
}

$ticket_id = $_GET['id'];
$user_id = $_SESSION['user_id'];

// 1. Verify Ownership
$stmt = $pdo->prepare("SELECT * FROM tickets WHERE id = ? AND user_id = ?");
$stmt->execute([$ticket_id, $user_id]);
$ticket = $stmt->fetch();

if (!$ticket) { echo "<div class='container' style='padding:50px;'><h2>Access Denied</h2></div>"; include 'includes/footer.php'; exit(); }

// 2. Handle Reply & Upload
if (isset($_POST['reply'])) {
    $msg = trim($_POST['message']);
    $file_path = NULL;

    // Handle File Upload
    if (!empty($_FILES['attachment']['name'])) {
        $allowed = ['jpg', 'jpeg', 'png', 'webp', 'pdf'];
        $ext = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, $allowed) && $_FILES['attachment']['size'] <= 5242880) { // 5MB
            $target = "uploads/tickets/" . time() . "_" . rand(100,999) . "." . $ext;
            if (!is_dir("uploads/tickets/")) mkdir("uploads/tickets/", 0777, true);
            if (move_uploaded_file($_FILES['attachment']['tmp_name'], $target)) {
                $file_path = $target;
            }
        }
    }

    if (!empty($msg) || $file_path) {
        $pdo->prepare("INSERT INTO ticket_messages (ticket_id, sender, message, attachment) VALUES (?, 'user', ?, ?)")
            ->execute([$ticket_id, $msg, $file_path]);
        $pdo->prepare("UPDATE tickets SET status = 'open' WHERE id = ?")->execute([$ticket_id]); 
        header("Location: view_ticket.php?id=$ticket_id"); exit();
    }
}

// 3. Fetch Messages
$msgs = $pdo->prepare("SELECT * FROM ticket_messages WHERE ticket_id = ? ORDER BY created_at ASC");
$msgs->execute([$ticket_id]);
$messages = $msgs->fetchAll();
?>

<style>
    .chat-box { background: #f9f9f9; padding: 20px; border-radius: 10px; max-height: 500px; overflow-y: auto; margin-bottom: 20px; border: 1px solid #eee; }
    .msg { margin-bottom: 15px; padding: 15px; border-radius: 8px; max-width: 80%; position: relative; }
    .msg-user { background: #d4edda; margin-left: auto; text-align: right; border-bottom-right-radius: 0; color: #155724; }
    .msg-admin { background: #fff; border: 1px solid #ddd; margin-right: auto; border-bottom-left-radius: 0; }
    .time { font-size: 11px; color: #888; display: block; margin-top: 5px; }
    .attachment-img { max-width: 100%; border-radius: 5px; margin-top: 10px; border: 1px solid rgba(0,0,0,0.1); display: block; }
    .attachment-link { display: inline-block; margin-top: 5px; font-size: 12px; color: #3498db; text-decoration: none; }
</style>

<div class="container" style="padding-top: 30px; max-width: 800px;">
    
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h2 style="margin:0;">Ticket #<?php echo $ticket['id']; ?></h2>
        <span class="badge" style="background: <?php echo $ticket['status']=='closed'?'gray':'green'; ?>; color: white; padding: 5px 10px; border-radius: 4px;">
            <?php echo ucfirst($ticket['status']); ?>
        </span>
    </div>
    <h4 style="margin-top:0; color:#555; border-bottom:1px solid #eee; padding-bottom:15px;"><?php echo htmlspecialchars($ticket['subject']); ?></h4>

    <div class="chat-box">
        <?php foreach($messages as $m): ?>
            <div class="msg <?php echo $m['sender'] == 'user' ? 'msg-user' : 'msg-admin'; ?>">
                <strong><?php echo $m['sender'] == 'user' ? 'You' : 'Support Team'; ?></strong>
                <p style="margin: 5px 0;"><?php echo nl2br(htmlspecialchars($m['message'])); ?></p>
                
                <?php if($m['attachment']): ?>
                    <?php $ext = pathinfo($m['attachment'], PATHINFO_EXTENSION); ?>
                    <?php if(in_array($ext, ['jpg','jpeg','png','webp'])): ?>
                        <a href="<?php echo $m['attachment']; ?>" target="_blank">
                            <img src="<?php echo $m['attachment']; ?>" class="attachment-img">
                        </a>
                    <?php else: ?>
                        <a href="<?php echo $m['attachment']; ?>" target="_blank" class="attachment-link">
                            <i class="fas fa-paperclip"></i> View Attachment
                        </a>
                    <?php endif; ?>
                <?php endif; ?>

                <span class="time"><?php echo date('d M h:i A', strtotime($m['created_at'])); ?></span>
            </div>
        <?php endforeach; ?>
    </div>

    <?php if($ticket['status'] != 'closed'): ?>
        <form method="POST" enctype="multipart/form-data" style="background:white; padding:15px; border:1px solid #eee; border-radius:8px;">
            <textarea name="message" placeholder="Type your reply..." style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; height: 80px; box-sizing: border-box;"></textarea>
            
            <div style="display:flex; justify-content:space-between; align-items:center; margin-top:10px;">
                <input type="file" name="attachment" style="font-size:12px;">
                <button type="submit" name="reply" class="btn btn-primary" style="width: auto; padding: 8px 20px;">Send Reply</button>
            </div>
        </form>
    <?php else: ?>
        <div style="text-align: center; background: #f1f1f1; padding: 15px; border-radius: 8px; color: #666;">
            This ticket is closed. <a href="support.php">Open a new ticket</a> if you need more help.
        </div>
    <?php endif; ?>

</div>

<?php include 'includes/footer.php'; ?>