<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
   header('Location: login.php');
   exit();
}

// Get ticket ID
$ticket_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Get ticket details
$sql = "SELECT t.*, u.full_name, u.email 
       FROM support_tickets t
       JOIN users u ON t.user_id = u.user_id 
       WHERE t.ticket_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $ticket_id);
$stmt->execute();
$ticket = $stmt->get_result()->fetch_assoc();

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

// Get ticket attachments
$sql = "SELECT * FROM ticket_attachments WHERE ticket_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $ticket_id);
$stmt->execute();
$attachments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get ticket comments/responses
$sql = "SELECT c.*, u.full_name 
       FROM ticket_comments c
       JOIN users u ON c.user_id = u.user_id 
       WHERE c.ticket_id = ?
       ORDER BY c.created_at ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $ticket_id);
$stmt->execute();
$comments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Handle new comment submission...
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['comment'])) {
   $comment = trim($_POST['comment']);
   if (!empty($comment)) {
       $sql = "INSERT INTO ticket_comments (ticket_id, user_id, comment) VALUES (?, ?, ?)";
       $stmt = $conn->prepare($sql);
       $stmt->bind_param('iis', $ticket_id, $_SESSION['user_id'], $comment);
       if ($stmt->execute()) {
           header("Location: view_ticket.php?id=$ticket_id");
           exit();
       }
   }
}

?>

<!DOCTYPE html>
<html>
<head>
   <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Ticket')); ?>
   <?php include 'layouts/head-css.php'; ?>
   <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
   <div id="layout-wrapper">
       <?php include 'layouts/menu.php'; ?>
       
       <div class="main-content">
           <div class="page-content">
               <div class="container-fluid">
                   <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Support', 'title' => 'Ticket Details')); ?>

                   <div class="row justify-content-center">
                       <div class="col-xl-8">
                           <div class="card">
                               <div class="card-header d-flex justify-content-between align-items-center">
                                   <div>
                                       <h4 class="card-title mb-0">Ticket #<?php echo $ticket_id; ?></h4>
                                       <small class="text-muted">Created on <?php echo date('d M Y H:i', strtotime($ticket['created_at'])); ?></small>
                                   </div>
                                   <span class="badge bg-<?php 
                                       echo $ticket['status'] === 'OPEN' ? 'success' : 
                                            ($ticket['status'] === 'CLOSED' ? 'danger' : 'warning'); 
                                   ?>"><?php echo $ticket['status']; ?></span>
                               </div>
                               <div class="card-body">
                                   <div class="mb-4">
                                       <h5><?php echo htmlspecialchars($ticket['subject']); ?></h5>
                                       <div class="d-flex gap-2 text-muted small mb-3">
                                           <span><i class="ri-user-3-line"></i> <?php echo htmlspecialchars($ticket['full_name']); ?></span>
                                           <span><i class="ri-mail-line"></i> <?php echo htmlspecialchars($ticket['email']); ?></span>
                                           <span><i class="ri-flag-line"></i> <?php echo ucfirst($ticket['priority']); ?> Priority</span>
                                           <span><i class="ri-folder-line"></i> <?php echo ucfirst($ticket['category']); ?></span>
                                       </div>
                                       <div class="border rounded p-3 bg-light">
                                           <?php echo nl2br(htmlspecialchars($ticket['description'])); ?>
                                       </div>
                                   </div>

                                   <?php if (!empty($attachments)): ?>
                                   <div class="mb-4">
                                       <h6 class="mb-2">Attachments</h6>
                                       <div class="d-flex gap-2">
                                           <?php foreach($attachments as $attachment): ?>
                                               <a href="<?php echo $attachment['file_path']; ?>" 
                                                  class="btn btn-soft-primary btn-sm" download>
                                                   <i class="ri-file-line me-1"></i>
                                                   <?php echo htmlspecialchars($attachment['file_name']); ?>
                                               </a>
                                           <?php endforeach; ?>
                                       </div>
                                   </div>
                                   <?php endif; ?>

                                   <?php if (!empty($comments)): ?>
                                   <div class="mb-4">
                                       <h6 class="mb-3">Comments</h6>
                                       <?php foreach($comments as $comment): ?>
                                           <div class="d-flex mb-3">
                                               <div class="flex-shrink-0">
                                                   <div class="avatar-sm">
                                                       <span class="avatar-title rounded-circle bg-primary">
                                                           <?php echo strtoupper(substr($comment['full_name'], 0, 1)); ?>
                                                       </span>
                                                   </div>
                                               </div>
                                               <div class="flex-grow-1 ms-3">
                                                   <h6 class="mb-1"><?php echo htmlspecialchars($comment['full_name']); ?></h6>
                                                   <small class="text-muted">
                                                       <?php echo date('d M Y H:i', strtotime($comment['created_at'])); ?>
                                                   </small>
                                                   <div class="mt-2">
                                                       <?php echo nl2br(htmlspecialchars($comment['comment'])); ?>
                                                   </div>
                                               </div>
                                           </div>
                                       <?php endforeach; ?>
                                   </div>
                                   <?php endif; ?>

                                   <?php if ($ticket['status'] !== 'CLOSED'): ?>
                                   <div>
                                       <h6 class="mb-3">Add Comment</h6>
                                       <form method="POST">
                                           <div class="mb-3">
                                               <textarea class="form-control" name="comment" rows="3" required></textarea>
                                           </div>
                                           <div class="text-end">
                                               <button type="submit" class="btn btn-primary">
                                                   <i class="ri-send-plane-line align-bottom me-1"></i> Send Response
                                               </button>
                                           </div>
                                       </form>
                                   </div>
                                   <?php endif; ?>
                               </div>
                           </div>
                       </div>

                       <?php if ($_SESSION['role_id'] === 1): ?>
                       <div class="col-xl-4">
                           <div class="card">
                               <div class="card-header">
                                   <h4 class="card-title mb-0">Ticket Management</h4>
                               </div>
                               <div class="card-body">
                                   <form action="update_ticket_status.php" method="POST">
                                       <input type="hidden" name="ticket_id" value="<?php echo $ticket_id; ?>">
                                       
                                       <div class="mb-3">
                                           <label class="form-label">Update Status</label>
                                           <select name="status" class="form-select" required>
                                               <option value="">Select Status</option>
                                               <option value="OPEN" <?php echo $ticket['status'] === 'OPEN' ? 'selected' : ''; ?>>Open</option>
                                               <option value="IN_PROGRESS" <?php echo $ticket['status'] === 'IN_PROGRESS' ? 'selected' : ''; ?>>In Progress</option>
                                               <option value="CLOSED" <?php echo $ticket['status'] === 'CLOSED' ? 'selected' : ''; ?>>Closed</option>
                                           </select>
                                       </div>

                                       <div class="mb-3">
                                           <label class="form-label">Update Priority</label>
                                           <select name="priority" class="form-select" required>
                                               <option value="">Select Priority</option>
                                               <option value="low" <?php echo $ticket['priority'] === 'low' ? 'selected' : ''; ?>>Low</option>
                                               <option value="medium" <?php echo $ticket['priority'] === 'medium' ? 'selected' : ''; ?>>Medium</option>
                                               <option value="high" <?php echo $ticket['priority'] === 'high' ? 'selected' : ''; ?>>High</option>
                                               <option value="urgent" <?php echo $ticket['priority'] === 'urgent' ? 'selected' : ''; ?>>Urgent</option>
                                           </select>
                                       </div>

                                       <div class="mb-3">
                                           <label class="form-label">Internal Notes</label>
                                           <textarea name="internal_notes" class="form-control" rows="3"><?php echo htmlspecialchars($ticket['internal_notes'] ?? ''); ?></textarea>
                                       </div>

                                       <div class="text-end">
                                           <button type="submit" class="btn btn-primary">
                                               Update Ticket
                                           </button>
                                       </div>
                                   </form>
                               </div>
                           </div>

                           <div class="card">
                               <div class="card-header">
                                   <h4 class="card-title mb-0">Activity Log</h4>
                               </div>
                               <div class="card-body">
                                   <div class="timeline">
                                       <?php
                                       $sql = "SELECT * FROM ticket_activity_log 
                                               WHERE ticket_id = ? 
                                               ORDER BY created_at DESC";
                                       $stmt = $conn->prepare($sql);
                                       $stmt->bind_param('i', $ticket_id);
                                       $stmt->execute();
                                       $activities = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

                                       foreach($activities as $activity):
                                       ?>
                                       <div class="timeline-item">
                                           <i class="ri-record-circle-line timeline-point"></i>
                                           <div class="timeline-content">
                                               <div>
                                                   <?php echo htmlspecialchars($activity['description']); ?>
                                                   <small class="text-muted ms-1">
                                                       <?php echo date('d M H:i', strtotime($activity['created_at'])); ?>
                                                   </small>
                                               </div>
                                           </div>
                                       </div>
                                       <?php endforeach; ?>
                                   </div>
                               </div>
                           </div>
                       </div>
                       <?php endif; ?>
                   </div>
               </div>
           </div>
           <?php include 'layouts/footer.php'; ?>
       </div>
   </div>

   <?php include 'layouts/vendor-scripts.php'; ?>
   <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<?php if (isset($_SESSION['success_alert'])): ?>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        Swal.fire({
            title: '<?php echo $_SESSION['success_alert']['title']; ?>',
            text: '<?php echo $_SESSION['success_alert']['text']; ?>',
            icon: '<?php echo $_SESSION['success_alert']['icon']; ?>',
            confirmButtonText: 'OK'
        });
    });
</script>
<?php unset($_SESSION['success_alert']); endif; ?>

</body>
</html>