<?php
require 'auth_check.php';
require '../config/db.php';

$id = $_GET['id'];

// Close Ticket
if(isset($_GET['close'])) {
    $pdo->prepare("UPDATE tickets SET status='closed' WHERE id=?")->execute([$id]);
    header("Location: ticket_view.php?id=$id"); exit();
}

// Reply & Upload
if(isset($_POST['reply'])) {
    $msg = trim($_POST['message']);
    $file_path = NULL;

    if (!empty($_FILES['attachment']['name'])) {
        $ext = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        $target = "../uploads/tickets/" . time() . "_admin_" . 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 = str_replace("../", "", $target); // Fix path for DB
        }
    }

    $pdo->prepare("INSERT INTO ticket_messages (ticket_id, sender, message, attachment) VALUES (?, 'admin', ?, ?)")
        ->execute([$id, $msg, $file_path]);
    $pdo->prepare("UPDATE tickets SET status='answered' WHERE id=?")->execute([$id]);
    header("Location: ticket_view.php?id=$id"); exit();
}

$ticket = $pdo->query("SELECT t.*, u.name, u.email FROM tickets t JOIN users u ON t.user_id = u.id WHERE t.id=$id")->fetch();
$msgs = $pdo->query("SELECT * FROM ticket_messages WHERE ticket_id=$id ORDER BY created_at ASC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Reply Ticket</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .chat-wrap { background: white; padding: 20px; border-radius: 8px; max-height: 500px; overflow-y: auto; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        .msg { padding: 15px; margin-bottom: 15px; border-radius: 5px; max-width: 85%; position: relative; }
        .msg-user { background: #f1f1f1; border-left: 4px solid #3498db; }
        .msg-admin { background: #e8f8f5; border-right: 4px solid #2ecc71; margin-left: auto; text-align: right; }
        .attachment-img { max-width: 200px; border-radius: 5px; margin-top: 10px; border: 1px solid #ccc; display:block; }
        .msg-admin .attachment-img { margin-left: auto; }
    </style>
</head>
<body>
    <div class="sidebar">
        <?php include 'sidebar.php'; ?>
    </div>

    <div class="content">
        <div style="display:flex; justify-content:space-between; margin-bottom:20px;">
            <h2><a href="support.php" style="text-decoration:none; color:#333;">&larr;</a> Ticket #<?php echo $id; ?>: <?php echo htmlspecialchars($ticket['subject']); ?></h2>
            <?php if($ticket['status']!='closed'): ?>
                <a href="ticket_view.php?id=<?php echo $id; ?>&close=1" class="btn btn-primary" style="background:#e74c3c;">Close Ticket</a>
            <?php endif; ?>
        </div>

        <div class="chat-wrap">
            <?php foreach($msgs as $m): ?>
                <div class="msg <?php echo $m['sender']=='user'?'msg-user':'msg-admin'; ?>">
                    <strong><?php echo $m['sender']=='user'? $ticket['name'] : 'You'; ?></strong><br>
                    <?php echo nl2br(htmlspecialchars($m['message'])); ?>
                    
                    <?php if($m['attachment']): ?>
                        <br>
                        <a href="../<?php echo $m['attachment']; ?>" target="_blank">
                            <img src="../<?php echo $m['attachment']; ?>" class="attachment-img">
                        </a>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>

        <?php if($ticket['status']!='closed'): ?>
        <form method="POST" enctype="multipart/form-data" style="margin-top: 20px; background: white; padding: 20px; border-radius: 8px;">
            <textarea name="message" style="width:100%; height:100px; padding:10px; border:1px solid #ddd; border-radius:5px;" placeholder="Reply to customer..."></textarea>
            
            <div style="margin-top:10px; display:flex; justify-content:space-between; align-items:center;">
                <input type="file" name="attachment">
                <button type="submit" name="reply" class="btn btn-primary">Send Reply</button>
            </div>
        </form>
        <?php endif; ?>
    </div>
</body>
</html>