<?php
session_start();
if (!isset($_SESSION['username'])) { header("location:login"); exit; }
ob_start();
include 'master.php';

$id = (int)($_GET['id'] ?? 0);
if (!$id) { header("location:support-tickets"); exit; }

// Handle reply POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_message'])) {
    $reply   = trim($_POST['reply_message']);
    $status  = trim($_POST['ticket_status'] ?? 'Open');
    if (!empty($reply)) {
        $stmt = $conn->prepare("INSERT INTO support_replies (ticket_id, sender, message) VALUES (?, 'admin', ?)");
        $stmt->bind_param('is', $id, $reply);
        $stmt->execute();
        $stmt->close();
    }
    $upd = $conn->prepare("UPDATE support_tickets SET status = ? WHERE id = ?");
    $upd->bind_param('si', $status, $id);
    $upd->execute();
    $upd->close();
    ob_end_clean();
    header("location:view-ticket?id=$id&replied=1");
    exit;
}

$res    = $conn->query("SELECT * FROM support_tickets WHERE id = '$id' LIMIT 1");
$ticket = $res ? $res->fetch_assoc() : null;
if (!$ticket) { header("location:support-tickets"); exit; }

// Mark this ticket as read by admin
$conn->query("UPDATE support_tickets SET admin_read = 1 WHERE id = '$id'");

$replies = $conn->query("SELECT * FROM support_replies WHERE ticket_id = '$id' ORDER BY id ASC");
?>
		<!--page-wrapper-->
		<div class="page-wrapper">
			<div class="page-content-wrapper">
				<div class="page-content">
					<div class="page-breadcrumb d-none d-md-flex align-items-center mb-3">
						<div class="breadcrumb-title pr-3">Support</div>
						<div class="pl-3">
							<nav aria-label="breadcrumb">
								<ol class="breadcrumb mb-0 p-0">
									<li class="breadcrumb-item"><a href="support-tickets">Support Tickets</a></li>
									<li class="breadcrumb-item active" aria-current="page">Ticket #<?php echo $id; ?></li>
								</ol>
							</nav>
						</div>
					</div><br>

					<?php if (!empty($_GET['replied'])): ?>
						<div class="alert alert-success alert-dismissible fade show" role="alert">
							Reply sent successfully.
							<button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
						</div>
					<?php endif; ?>

					<div class="row">
						<!-- Ticket Info + Thread -->
						<div class="col-lg-8">
							<div class="card mb-4">
								<div class="card-body">
									<h5 class="card-title"><?php echo htmlspecialchars($ticket['subject']); ?></h5>
									<p class="text-muted small mb-2">
										From: <strong><?php echo htmlspecialchars($ticket['user_name']); ?></strong>
										(<?php echo htmlspecialchars($ticket['user_email']); ?>)
										&middot; <?php echo $ticket['date_added']; ?>
									</p>
									<hr/>
									<!-- Original message -->
									<div class="p-3 bg-light rounded mb-3">
										<p class="small font-weight-bold text-muted mb-1">User</p>
										<p class="mb-0" style="white-space:pre-line;"><?php echo htmlspecialchars($ticket['message']); ?></p>
									</div>

									<!-- Reply thread -->
									<?php if ($replies && $replies->num_rows > 0): ?>
										<?php foreach ($replies as $rep): ?>
											<div class="p-3 rounded mb-2 <?php echo $rep['sender'] === 'admin' ? 'border-left border-primary' : 'bg-light'; ?>" style="<?php echo $rep['sender'] === 'admin' ? 'background:#f0f4ff;border-left:4px solid #0d6efd!important;' : ''; ?>">
												<p class="small font-weight-bold mb-1 <?php echo $rep['sender'] === 'admin' ? 'text-primary' : 'text-muted'; ?>">
													<?php echo $rep['sender'] === 'admin' ? 'Support Team' : 'User'; ?>
													&middot; <span class="font-weight-normal"><?php echo $rep['date_added']; ?></span>
												</p>
												<p class="mb-0" style="white-space:pre-line;"><?php echo htmlspecialchars($rep['message']); ?></p>
											</div>
										<?php endforeach; ?>
									<?php endif; ?>
								</div>
							</div>
						</div>

						<!-- Reply + Status Panel -->
						<div class="col-lg-4">
							<div class="card">
								<div class="card-body">
									<h5 class="card-title">Reply &amp; Update Status</h5>
									<form method="POST">
										<div class="form-group">
											<label class="font-weight-bold">Status</label>
											<select name="ticket_status" class="form-control">
												<?php foreach (['Open','In Progress','Resolved','Closed'] as $s): ?>
													<option value="<?php echo $s; ?>" <?php echo $ticket['status'] === $s ? 'selected' : ''; ?>><?php echo $s; ?></option>
												<?php endforeach; ?>
											</select>
										</div>
										<div class="form-group">
											<label class="font-weight-bold">Reply Message</label>
											<textarea name="reply_message" rows="6" class="form-control" placeholder="Type your reply here..."></textarea>
										</div>
										<button type="submit" class="btn btn-primary btn-block">
											<i class="bx bx-send mr-1"></i> Send Reply
										</button>
									</form>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="overlay toggle-btn-mobile"></div>
		<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include 'footer.php'; ?>
