
<?php 
session_start();
include('includes/head.php');

// Check admin session
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System Admin';
$admin_role = $_SESSION['admin_role'] ?: 'admin';

// PIN for confirmation
$admin_pin = "1234";

// Handle actions
$action = isset($_GET['action']) ? $_GET['action'] : '';
$ticket_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
    $target_id = isset($_POST['ticket_id']) ? intval($_POST['ticket_id']) : 0;
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'update_status':
                $new_status = isset($_POST['status']) ? $_POST['status'] : '';
                $priority = isset($_POST['priority']) ? $_POST['priority'] : '';
                $assign_to = isset($_POST['assign_to']) ? intval($_POST['assign_to']) : 0;
                $internal_note = isset($_POST['internal_note']) ? mysqli_real_escape_string($conn, $_POST['internal_note']) : '';
                
                if ($target_id > 0) {
                    // Get ticket and user details before update for notification
                    $ticket_info_sql = "SELECT t.*, u.first_name, u.email, u.username 
                                       FROM support_tickets t
                                       LEFT JOIN users u ON t.user_id = u.id
                                       WHERE t.id = $target_id";
                    $ticket_info_result = mysqli_query($conn, $ticket_info_sql);
                    $ticket_info = mysqli_fetch_assoc($ticket_info_result);
                    
                    $updates = array();
                    $old_status = $ticket_info['status'];
                    $old_priority = $ticket_info['priority'];
                    $old_assigned = $ticket_info['assigned_to'];
                    
                    if ($new_status) $updates[] = "status = '$new_status'";
                    if ($priority) $updates[] = "priority = '$priority'";
                    if ($assign_to > 0) $updates[] = "assigned_to = $assign_to";
                    if ($assign_to == 0) $updates[] = "assigned_to = NULL";
                    
                    if (!empty($updates)) {
                        $update_sql = "UPDATE support_tickets SET " . implode(', ', $updates) . ", updated_at = NOW() WHERE id = $target_id";
                        
                        if (mysqli_query($conn, $update_sql)) {
                            // Add internal note
                            if ($internal_note) {
                                $note_sql = "INSERT INTO ticket_replies (ticket_id, user_id, message, is_admin_reply, created_at) 
                                            VALUES ($target_id, $admin_id, '[Internal Note] $internal_note', 1, NOW())";
                                mysqli_query($conn, $note_sql);
                            }
                            
                            // Log activity
                            logAdminActivity(
                                'Ticket Status Updated',
                                "Updated ticket #$target_id to $new_status",
                                'Support',
                                $target_id,
                                'support_tickets'
                            );
                            
                            // NOTIFICATION: Ticket Status Updated (USER)
                            if ($new_status && $new_status != $old_status) {
                                $mail_subject = "Support Ticket #" . $ticket_info['ticket_number'] . " Status Updated";
                                $mail_message = "<!-- Content Section -->
                                                <div class='email-content'>
                                                    <h2 class='greeting'>Hello <span class='user-name'>" . $ticket_info['first_name'] . "</span>,</h2>
                                                    
                                                    <p class='message'>
                                                        The status of your support ticket has been updated by our support team.
                                                    </p>

                                                    <!-- Ticket Details -->
                                                    <div class='details-section'>
                                                        <div class='detail-box'>
                                                            <strong>Ticket Number:</strong> " . $ticket_info['ticket_number'] . "<br>
                                                            <strong>Subject:</strong> " . htmlspecialchars($ticket_info['subject']) . "<br>
                                                            <strong>Previous Status:</strong> <span style='color: #6c757d;'>" . ucfirst(str_replace('_', ' ', $old_status)) . "</span><br>
                                                            <strong>New Status:</strong> <span style='color: " . 
                                                                ($new_status == 'resolved' ? '#28a745' : 
                                                                ($new_status == 'in_progress' ? '#ffc107' : 
                                                                ($new_status == 'closed' ? '#6c757d' : '#dc3545'))) . "; font-weight: bold;'>" . 
                                                                ucfirst(str_replace('_', ' ', $new_status)) . "</span><br>
                                                            <strong>Updated By:</strong> " . $admin_name . "<br>
                                                            <strong>Update Date:</strong> " . date('F j, Y g:i A') . "
                                                        </div>
                                                    </div>";

                                // Add priority change notification if changed
                                if ($priority && $priority != $old_priority) {
                                    $mail_message .= "
                                                    <!-- Priority Update -->
                                                    <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                        <h4 style='color: #495057;'>📊 Priority Updated</h4>
                                                        <p style='color: #495057;'>
                                                            <strong>Previous Priority:</strong> " . ucfirst($old_priority) . "<br>
                                                            <strong>New Priority:</strong> <span style='color: " . 
                                                                ($priority == 'urgent' ? '#dc3545' : 
                                                                ($priority == 'high' ? '#ffc107' : 
                                                                ($priority == 'medium' ? '#17a2b8' : '#28a745'))) . "; font-weight: bold;'>" . 
                                                                ucfirst($priority) . "</span>
                                                        </p>
                                                    </div>";
                                }

                                // Add assignment notification if changed
                                if ($assign_to > 0 && $assign_to != $old_assigned) {
                                    // Get assigned admin name
                                    $admin_name_sql = "SELECT name FROM admins WHERE id = $assign_to";
                                    $admin_name_result = mysqli_query($conn, $admin_name_sql);
                                    $assigned_admin = mysqli_fetch_assoc($admin_name_result);
                                    
                                    $mail_message .= "
                                                    <!-- Assignment Update -->
                                                    <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                        <h4 style='color: #0056b3;'>👤 Ticket Assignment</h4>
                                                        <p style='color: #0056b3;'>
                                                            Your ticket has been assigned to: <strong>" . $assigned_admin['name'] . "</strong>
                                                        </p>
                                                    </div>";
                                }

                                // Add internal note summary if exists
                                if ($internal_note) {
                                    $mail_message .= "
                                                    <!-- Internal Note (Summary) -->
                                                    <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                        <h4 style='color: #856404;'>📝 Support Note</h4>
                                                        <p style='color: #856404;'>
                                                            Our support team has added an internal note regarding your ticket.
                                                        </p>
                                                    </div>";
                                }

                                $mail_message .= "
                                                    <!-- What This Means -->
                                                    <div class='next-steps'>
                                                        <h3 style='color: #2c3e50;'>What This Means</h3>
                                                        <p style='color: #6c757d;'>" . 
                                                            ($new_status == 'resolved' ? 
                                                                'Your issue has been resolved. If you experience the same issue again, please create a new ticket.' : 
                                                            ($new_status == 'in_progress' ? 
                                                                'Our support team is actively working on your issue and will respond shortly.' : 
                                                            ($new_status == 'closed' ? 
                                                                'This ticket has been closed. You can reopen it if you need further assistance.' : 
                                                                'Your ticket is open and awaiting response from our support team.'))) . 
                                                        "</p>
                                                    </div>

                                                    <!-- Action Buttons -->
                                                    <div style='text-align: center; margin: 30px 0;'>
                                                        <a href='" . $myUrl . "/support/ticket-details.php?id=" . $target_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                            View Ticket Details
                                                        </a>
                                                        <a href='" . $myUrl . "/support.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                            View All Tickets
                                                        </a>
                                                    </div>

                                                    <!-- Support Section -->
                                                    <div class='support-section'>
                                                        <p class='support-text'>Need further assistance?</p>
                                                        <a href='" . $myUrl . "/support.php' class='support-link'>Create New Ticket</a>
                                                    </div>
                                                </div>";

                                // Send user notification
                                $user_email = $ticket_info['email'];
                                $first_name = $ticket_info['first_name'];
                                require_once("../proccess/mail_sender.php");
                            }
                            
                            // NOTIFICATION: Ticket Assigned (ADMIN - to assigned admin)
                            if ($assign_to > 0 && $assign_to != $old_assigned) {
                                // Get assigned admin details
                                $assigned_admin_sql = "SELECT name, email FROM admins WHERE id = $assign_to";
                                $assigned_admin_result = mysqli_query($conn, $assigned_admin_sql);
                                $assigned_admin = mysqli_fetch_assoc($assigned_admin_result);
                                
                                if ($assigned_admin) {
                                    $admin_mail_subject = "New Ticket Assignment - " . $ticket_info['ticket_number'];
                                    $admin_mail_message = "<!-- Content Section -->
                                                        <div class='email-content'>
                                                            <h2 class='greeting'>Ticket Assigned to You</h2>
                                                            
                                                            <p class='message'>
                                                                A support ticket has been assigned to you by " . $admin_name . ".
                                                            </p>

                                                            <!-- Ticket Details -->
                                                            <div class='details-section'>
                                                                <div class='detail-box'>
                                                                    <strong>Ticket Number:</strong> " . $ticket_info['ticket_number'] . "<br>
                                                                    <strong>Subject:</strong> " . htmlspecialchars($ticket_info['subject']) . "<br>
                                                                    <strong>Priority:</strong> <span style='color: " . 
                                                                        ($ticket_info['priority'] == 'urgent' ? '#dc3545' : 
                                                                        ($ticket_info['priority'] == 'high' ? '#ffc107' : 
                                                                        ($ticket_info['priority'] == 'medium' ? '#17a2b8' : '#28a745'))) . "; font-weight: bold;'>" . 
                                                                        ucfirst($ticket_info['priority']) . "</span><br>
                                                                    <strong>Category:</strong> " . ucfirst(str_replace('_', ' ', $ticket_info['category'])) . "<br>
                                                                    <strong>User:</strong> " . $ticket_info['username'] . " (" . $ticket_info['email'] . ")<br>
                                                                    <strong>Assigned By:</strong> " . $admin_name . "<br>
                                                                    <strong>Assignment Date:</strong> " . date('F j, Y g:i A') . "
                                                                </div>
                                                            </div>

                                                            <!-- Admin Actions -->
                                                            <div style='text-align: center; margin: 30px 0;'>
                                                                <a href='" . $myUrl . "/admin/support/ticket.php?id=" . $target_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                                    View Assigned Ticket
                                                                </a>
                                                                <a href='" . $myUrl . "/admin/support/tickets.php?assigned_to=" . $assign_to . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                                    View My Tickets
                                                                </a>
                                                            </div>
                                                        </div>";

                                    // Send admin notification
                                    require_once("../proccess/admin_mailer.php");
                                }
                            }
                            
                            $success = "Ticket updated successfully!";
                        } else {
                            $error = "Failed to update ticket.";
                        }
                    }
                }
                break;
                
            case 'add_reply':
                $message = isset($_POST['message']) ? mysqli_real_escape_string($conn, $_POST['message']) : '';
                
                if ($target_id > 0 && $message) {
                    // Get ticket and user details before update for notification
                    $ticket_info_sql = "SELECT t.*, u.first_name, u.email, u.username 
                                       FROM support_tickets t
                                       LEFT JOIN users u ON t.user_id = u.id
                                       WHERE t.id = $target_id";
                    $ticket_info_result = mysqli_query($conn, $ticket_info_sql);
                    $ticket_info = mysqli_fetch_assoc($ticket_info_result);
                    
                    // Add reply
                    $reply_sql = "INSERT INTO ticket_replies (ticket_id, user_id, message, is_admin_reply, created_at) 
                                 VALUES ($target_id, $admin_id, '$message', 1, NOW())";
                    
                    if (mysqli_query($conn, $reply_sql)) {
                        $reply_id = mysqli_insert_id($conn);
                        
                        // Update ticket status to in_progress if it was open
                        $update_sql = "UPDATE support_tickets SET status = 'in_progress', updated_at = NOW() WHERE id = $target_id AND status = 'open'";
                        mysqli_query($conn, $update_sql);
                        
                        // Log activity
                        logAdminActivity(
                            'Ticket Reply Added',
                            "Added reply to ticket #$target_id",
                            'Support',
                            $target_id,
                            'support_tickets'
                        );
                        
                        // NOTIFICATION: New Reply Added (USER)
                        $mail_subject = "New Reply on Ticket #" . $ticket_info['ticket_number'];
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Hello <span class='user-name'>" . $ticket_info['first_name'] . "</span>,</h2>
                                            
                                            <p class='message'>
                                                Our support team has replied to your ticket. Please check the response and let us know if you need further assistance.
                                            </p>

                                            <!-- Ticket Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Ticket Number:</strong> " . $ticket_info['ticket_number'] . "<br>
                                                    <strong>Subject:</strong> " . htmlspecialchars($ticket_info['subject']) . "<br>
                                                    <strong>Replied By:</strong> " . $admin_name . " (Support Team)<br>
                                                    <strong>Reply Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>Ticket Status:</strong> <span style='color: #ffc107; font-weight: bold;'>In Progress</span>
                                                </div>
                                            </div>

                                            <!-- Reply Message -->
                                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #495057;'>Support Team Response</h4>
                                                <div style='background: white; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; margin-top: 10px;'>
                                                    <p style='color: #495057; white-space: pre-wrap;'>" . nl2br(htmlspecialchars($message)) . "</p>
                                                </div>
                                            </div>

                                            <!-- Next Steps -->
                                            <div class='next-steps'>
                                                <h3 style='color: #2c3e50;'>📋 Next Steps</h3>
                                                <ul style='color: #6c757d;'>
                                                    <li>Review the support team's response above</li>
                                                    <li>Reply directly through your ticket dashboard</li>
                                                    <li>If your issue is resolved, you can close the ticket</li>
                                                    <li>Response time: Our team typically responds within 2-4 hours</li>
                                                </ul>
                                            </div>

                                            <!-- Action Buttons -->
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/support/ticket-details.php?id=" . $target_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                    View Reply
                                                </a>
                                                <a href='" . $myUrl . "/support.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                    Go to Support
                                                </a>
                                            </div>

                                            <!-- Support Section -->
                                            <div class='support-section'>
                                                <p class='support-text'>Was this reply helpful?</p>
                                                <p class='support-text'>If not, you can respond to this ticket directly.</p>
                                            </div>
                                        </div>";

                        // Send user notification
                        $user_email = $ticket_info['email'];
                        $first_name = $ticket_info['first_name'];
                        require_once("../proccess/mail_sender.php");
                        
                        $success = "Reply added successfully!";
                    } else {
                        $error = "Failed to add reply.";
                    }
                }
                break;
                
            case 'delete_ticket':
                if ($target_id > 0) {
                    // Get ticket info before deletion for notification
                    $ticket_sql = "SELECT t.*, u.first_name, u.email, u.username 
                                  FROM support_tickets t
                                  LEFT JOIN users u ON t.user_id = u.id
                                  WHERE t.id = $target_id";
                    $ticket_result = mysqli_query($conn, $ticket_sql);
                    $ticket_data = mysqli_fetch_assoc($ticket_result);
                    $ticket_number = $ticket_data['ticket_number'] ?: '';
                    $subject = $ticket_data['subject'] ?: '';
                    $user_email = $ticket_data['email'];
                    $first_name = $ticket_data['first_name'];
                    
                    // Delete ticket and replies
                    $delete_replies = "DELETE FROM ticket_replies WHERE ticket_id = $target_id";
                    $delete_ticket = "DELETE FROM support_tickets WHERE id = $target_id";
                    
                    mysqli_query($conn, $delete_replies);
                    if (mysqli_query($conn, $delete_ticket)) {
                        // Log activity
                        logAdminActivity(
                            'Ticket Deleted',
                            "Deleted ticket $ticket_number: $subject",
                            'Support',
                            $target_id,
                            'support_tickets'
                        );
                        
                        // NOTIFICATION: Ticket Deleted (USER)
                        if ($user_email) {
                            $mail_subject = "Support Ticket #" . $ticket_number . " - Deleted";
                            $mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                                
                                                <p class='message'>
                                                    This email confirms that your support ticket has been deleted from our system.
                                                </p>

                                                <!-- Ticket Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Ticket Number:</strong> " . $ticket_number . "<br>
                                                        <strong>Subject:</strong> " . htmlspecialchars($subject) . "<br>
                                                        <strong>Deleted By:</strong> " . $admin_name . " (Support Team)<br>
                                                        <strong>Deletion Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>Reason:</strong> Administrative action
                                                    </div>
                                                </div>

                                                <!-- Important Note -->
                                                <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #721c24;'>⚠️ Important</h4>
                                                    <p style='color: #721c24;'>
                                                        This ticket has been permanently deleted and cannot be recovered.<br>
                                                        If you still need assistance, please create a new support ticket.
                                                    </p>
                                                </div>

                                                <!-- Action Buttons -->
                                                <div style='text-align: center; margin: 30px 0;'>
                                                    <a href='" . $myUrl . "/support.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                        Create New Ticket
                                                    </a>
                                                </div>

                                                <!-- Support Section -->
                                                <div class='support-section'>
                                                    <p class='support-text'>If you didn't request this deletion or have questions, please contact us.</p>
                                                    <a href='" . $myUrl . "/contact.php' class='support-link'>Contact Support</a>
                                                </div>
                                            </div>";

                            // Send user notification
                            require_once("../proccess/mail_sender.php");
                        }
                        
                        $success = "Ticket deleted successfully!";
                    } else {
                        $error = "Failed to delete ticket.";
                    }
                }
                break;
                
            case 'create_ticket':
                // This would be handled in create_ticket.php file
                break;
        }
    }
}

// Get filter parameters
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$filter_priority = isset($_GET['priority']) ? $_GET['priority'] : '';
$filter_category = isset($_GET['category']) ? $_GET['category'] : '';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$assigned_to = isset($_GET['assigned_to']) ? intval($_GET['assigned_to']) : 0;
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build query
$sql = "SELECT t.*, u.username, u.email, a.name as assigned_admin 
        FROM support_tickets t 
        LEFT JOIN users u ON t.user_id = u.id 
        LEFT JOIN admins a ON t.assigned_to = a.id 
        WHERE 1=1";
$count_sql = "SELECT COUNT(*) as total FROM support_tickets WHERE 1=1";

// Apply filters
if ($filter_status) {
    $sql .= " AND t.status = '$filter_status'";
    $count_sql .= " AND status = '$filter_status'";
}

if ($filter_priority) {
    $sql .= " AND t.priority = '$filter_priority'";
    $count_sql .= " AND priority = '$filter_priority'";
}

if ($filter_category) {
    $sql .= " AND t.category = '$filter_category'";
    $count_sql .= " AND category = '$filter_category'";
}

if ($search) {
    $sql .= " AND (t.ticket_number LIKE '%$search%' OR t.subject LIKE '%$search%' OR u.username LIKE '%$search%' OR u.email LIKE '%$search%')";
    $count_sql .= " AND (ticket_number LIKE '%$search%' OR subject LIKE '%$search%')";
}

if ($assigned_to > 0) {
    $sql .= " AND t.assigned_to = $assigned_to";
    $count_sql .= " AND assigned_to = $assigned_to";
} elseif ($assigned_to == -1) {
    $sql .= " AND t.assigned_to IS NULL";
    $count_sql .= " AND assigned_to IS NULL";
}

if ($date_from && $date_to) {
    $sql .= " AND DATE(t.created_at) BETWEEN '$date_from' AND '$date_to'";
    $count_sql .= " AND DATE(created_at) BETWEEN '$date_from' AND '$date_to'";
} elseif ($date_from) {
    $sql .= " AND DATE(t.created_at) >= '$date_from'";
    $count_sql .= " AND DATE(created_at) >= '$date_from'";
} elseif ($date_to) {
    $sql .= " AND DATE(t.created_at) <= '$date_to'";
    $count_sql .= " AND DATE(created_at) <= '$date_to'";
}

// Add sorting
$sql .= " ORDER BY 
    CASE WHEN t.status = 'open' THEN 1 
         WHEN t.status = 'in_progress' THEN 2
         WHEN t.status = 'resolved' THEN 3
         ELSE 4 END,
    CASE WHEN t.priority = 'urgent' THEN 1
         WHEN t.priority = 'high' THEN 2
         WHEN t.priority = 'medium' THEN 3
         ELSE 4 END,
    t.created_at DESC";

// Execute query
$result = mysqli_query($conn, $sql);

// Get counts for stats
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) as open,
    SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
    SUM(CASE WHEN status = 'resolved' THEN 1 ELSE 0 END) as resolved,
    SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed,
    SUM(CASE WHEN priority = 'urgent' THEN 1 ELSE 0 END) as urgent,
    SUM(CASE WHEN priority = 'high' THEN 1 ELSE 0 END) as high,
    SUM(CASE WHEN priority = 'medium' THEN 1 ELSE 0 END) as medium,
    SUM(CASE WHEN priority = 'low' THEN 1 ELSE 0 END) as low
    FROM support_tickets";

$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

// Get admins for assignment
$admins_sql = "SELECT id, name, role FROM admins WHERE is_active = 1 ORDER BY role, name";
$admins_result = mysqli_query($conn, $admins_sql);

// Get unique categories
$categories_sql = "SELECT DISTINCT category FROM support_tickets WHERE category IS NOT NULL AND category != '' ORDER BY category";
$categories_result = mysqli_query($conn, $categories_sql);
?>


<!DOCTYPE html>
<html lang="en">
	
	<body class="hold-transition dark-skin sidebar-mini theme-primary fixed">
		
		<div class="wrapper">
		  	<div id="loader"></div>
		  	
		  <?php include('includes/header.php') ?>

		  <?php include('includes/sidebar.php') ?>

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-ticket-alt me-2"></i>Support Tickets Management</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createTicketModal">
												<i class="fas fa-plus me-1"></i> Create Ticket
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Stats Cards -->
										<div class="row mb-20">
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['total']; ?></h1>
														<p class="text-white mb-0">Total Tickets</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-danger pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['open']; ?></h1>
														<p class="text-white mb-0">Open</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['in_progress']; ?></h1>
														<p class="text-white mb-0">In Progress</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['resolved']; ?></h1>
														<p class="text-white mb-0">Resolved</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-info pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['urgent']; ?></h1>
														<p class="text-white mb-0">Urgent</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-dark pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['high']; ?></h1>
														<p class="text-white mb-0">High Priority</p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-12">
												<form method="GET" class="row">
													<div class="col-md-2">
														<div class="form-group">
															<label>Status</label>
															<select class="form-control" name="status" onchange="this.form.submit()">
																<option value="">All Status</option>
																<option value="open" <?php echo $filter_status == 'open' ? 'selected' : ''; ?>>Open</option>
																<option value="in_progress" <?php echo $filter_status == 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
																<option value="resolved" <?php echo $filter_status == 'resolved' ? 'selected' : ''; ?>>Resolved</option>
																<option value="closed" <?php echo $filter_status == 'closed' ? 'selected' : ''; ?>>Closed</option>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label>Priority</label>
															<select class="form-control" name="priority" onchange="this.form.submit()">
																<option value="">All Priority</option>
																<option value="urgent" <?php echo $filter_priority == 'urgent' ? 'selected' : ''; ?>>Urgent</option>
																<option value="high" <?php echo $filter_priority == 'high' ? 'selected' : ''; ?>>High</option>
																<option value="medium" <?php echo $filter_priority == 'medium' ? 'selected' : ''; ?>>Medium</option>
																<option value="low" <?php echo $filter_priority == 'low' ? 'selected' : ''; ?>>Low</option>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label>Category</label>
															<select class="form-control" name="category" onchange="this.form.submit()">
																<option value="">All Categories</option>
																<?php while ($cat = mysqli_fetch_assoc($categories_result)): ?>
																	<option value="<?php echo $cat['category']; ?>" <?php echo $filter_category == $cat['category'] ? 'selected' : ''; ?>>
																		<?php echo ucfirst(str_replace('_', ' ', $cat['category'])); ?>
																	</option>
																<?php endwhile; ?>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label>Assigned To</label>
															<select class="form-control" name="assigned_to" onchange="this.form.submit()">
																<option value="0">All Admins</option>
																<option value="-1" <?php echo $assigned_to == -1 ? 'selected' : ''; ?>>Unassigned</option>
																<?php while ($admin = mysqli_fetch_assoc($admins_result)): ?>
																	<option value="<?php echo $admin['id']; ?>" <?php echo $assigned_to == $admin['id'] ? 'selected' : ''; ?>>
																		<?php echo $admin['name'] . ' (' . $admin['role'] . ')'; ?>
																	</option>
																<?php endwhile; ?>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label>Date From</label>
															<input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>" onchange="this.form.submit()">
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label>Date To</label>
															<input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>" onchange="this.form.submit()">
														</div>
													</div>
													<div class="col-md-8">
														<div class="form-group">
															<label>Search</label>
															<div class="input-group">
																<input type="text" class="form-control" name="search" placeholder="Search tickets..." value="<?php echo htmlspecialchars($search); ?>">
																<button type="submit" class="btn btn-primary"><i class="fas fa-search"></i></button>
															</div>
														</div>
													</div>
													<div class="col-md-4">
														<div class="form-group">
															<label>&nbsp;</label>
															<div class="d-flex">
																<button type="submit" class="btn btn-primary me-2"><i class="fas fa-filter me-1"></i> Apply Filters</button>
																<?php if ($search || $filter_status || $filter_priority || $filter_category || $date_from || $date_to): ?>
																	<a href="support_tickets.php" class="btn btn-secondary">Clear Filters</a>
																<?php endif; ?>
															</div>
														</div>
													</div>
												</form>
											</div>
										</div>
										
										<?php if (isset($success)): ?>
											<div class="alert alert-success alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
											</div>
										<?php endif; ?>
										
										<?php if (isset($error)): ?>
											<div class="alert alert-danger alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
											</div>
										<?php endif; ?>
										
										<!-- Tickets Table -->
										<div class="table-responsive">
											<table class="table table-hover table-bordered" id="ticketsTable">
												<thead class="bg-light">
													<tr>
														<th>Ticket #</th>
														<th>Subject</th>
														<th>User</th>
														<th>Category</th>
														<th>Priority</th>
														<th>Status</th>
														<th>Assigned To</th>
														<th>Created</th>
														<th>Last Update</th>
														<th>Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($ticket = mysqli_fetch_assoc($result)): ?>
															<?php
															// Status colors
															$status_colors = array(
																'open' => 'danger',
																'in_progress' => 'warning',
																'resolved' => 'success',
																'closed' => 'secondary'
															);
															
															// Priority colors
															$priority_colors = array(
																'urgent' => 'danger',
																'high' => 'warning',
																'medium' => 'info',
																'low' => 'success'
															);
															
															$status_color = isset($status_colors[$ticket['status']]) ? $status_colors[$ticket['status']] : 'secondary';
															$priority_color = isset($priority_colors[$ticket['priority']]) ? $priority_colors[$ticket['priority']] : 'secondary';
															$created_date = date('M d, Y', strtotime($ticket['created_at']));
															$updated_date = $ticket['updated_at'] ? date('M d, Y', strtotime($ticket['updated_at'])) : '-';
															?>
															<tr>
																<td><strong><?php echo $ticket['ticket_number']; ?></strong></td>
																<td>
																	<p class="mb-0 fw-500"><?php echo htmlspecialchars($ticket['subject']); ?></p>
																	<small class="text-mute"><?php echo substr($ticket['description'], 0, 50) . '...'; ?></small>
																</td>
																<td>
																	<p class="mb-0"><?php echo htmlspecialchars($ticket['username']); ?></p>
																	<small class="text-mute"><?php echo htmlspecialchars($ticket['email']); ?></small>
																</td>
																<td>
																	<span class="badge bg-secondary">
																		<?php echo ucfirst(str_replace('_', ' ', $ticket['category'])); ?>
																	</span>
																</td>
																<td>
																	<span class="badge bg-<?php echo $priority_color; ?>">
																		<?php echo ucfirst($ticket['priority']); ?>
																	</span>
																</td>
																<td>
																	<span class="badge bg-<?php echo $status_color; ?>">
																		<?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
																	</span>
																</td>
																<td>
																	<?php if ($ticket['assigned_admin']): ?>
																		<p class="mb-0"><?php echo $ticket['assigned_admin']; ?></p>
																		<small class="text-mute">Assigned</small>
																	<?php else: ?>
																		<span class="badge bg-light text-dark">Unassigned</span>
																	<?php endif; ?>
																</td>
																<td>
																	<p class="mb-0"><?php echo $created_date; ?></p>
																	<small class="text-mute"><?php echo time_ago($ticket['created_at']); ?> ago</small>
																</td>
																<td>
																	<p class="mb-0"><?php echo $updated_date; ?></p>
																	<small class="text-mute">Updated</small>
																</td>
																<td>
																	<div class="btn-group">
																		<button type="button" class="btn btn-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">
																			<i class="fas fa-cog"></i>
																		</button>
																		<div class="dropdown-menu">
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#viewTicketModal" 
																			   data-ticket-id="<?php echo $ticket['id']; ?>">
																				<i class="fas fa-eye me-2"></i> View Details
																			</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#replyModal" 
																			   data-ticket-id="<?php echo $ticket['id']; ?>">
																				<i class="fas fa-reply me-2"></i> Reply
																			</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#updateTicketModal" 
																			   data-ticket-id="<?php echo $ticket['id']; ?>" 
																			   data-current-status="<?php echo $ticket['status']; ?>"
																			   data-current-priority="<?php echo $ticket['priority']; ?>">
																				<i class="fas fa-edit me-2"></i> Update Status
																			</a>
																			<div class="dropdown-divider"></div>
																			<a class="dropdown-item text-danger" href="#" onclick="confirmDelete(<?php echo $ticket['id']; ?>)">
																				<i class="fas fa-trash me-2"></i> Delete
																			</a>
																		</div>
																	</div>
																</td>
															</tr>
														<?php endwhile; ?>
													<?php else: ?>
														<tr>
															<td colspan="10" class="text-center py-20">
																<i class="fas fa-ticket-alt fa-2x text-mute mb-3"></i>
																<h5>No tickets found</h5>
																<p class="text-mute">Try adjusting your search or filters</p>
															</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
										
										<!-- Pagination would go here -->
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Viewing Ticket Details -->
		<div class="modal fade" id="viewTicketModal" tabindex="-1" aria-labelledby="viewTicketModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-xl">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="viewTicketModalLabel">Ticket Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="ticketDetails">
						<!-- Details will be loaded via AJAX -->
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
						<button type="button" class="btn btn-primary" onclick="replyToTicket()">Reply</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Modal for Updating Ticket Status -->
		<div class="modal fade" id="updateTicketModal" tabindex="-1" aria-labelledby="updateTicketModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="updateTicketModalLabel">Update Ticket</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="update_status">
							<input type="hidden" name="ticket_id" id="updateTicketId">
							
							<div class="mb-3">
								<label class="form-label">Status</label>
								<select class="form-control" name="status" required>
									<option value="open">Open</option>
									<option value="in_progress">In Progress</option>
									<option value="resolved">Resolved</option>
									<option value="closed">Closed</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Priority</label>
								<select class="form-control" name="priority" required>
									<option value="urgent">Urgent</option>
									<option value="high">High</option>
									<option value="medium">Medium</option>
									<option value="low">Low</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Assign To</label>
								<select class="form-control" name="assign_to">
									<option value="0">Unassigned</option>
									<?php mysqli_data_seek($admins_result, 0); ?>
									<?php while ($admin = mysqli_fetch_assoc($admins_result)): ?>
										<option value="<?php echo $admin['id']; ?>">
											<?php echo $admin['name'] . ' (' . $admin['role'] . ')'; ?>
										</option>
									<?php endwhile; ?>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Internal Note (Optional)</label>
								<textarea class="form-control" name="internal_note" rows="3" placeholder="Add internal note..."></textarea>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Update Ticket</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Replying to Ticket -->
		<div class="modal fade" id="replyModal" tabindex="-1" aria-labelledby="replyModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="replyModalLabel">Reply to Ticket</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="add_reply">
							<input type="hidden" name="ticket_id" id="replyTicketId">
							
							<div class="mb-3">
								<label class="form-label">Your Reply</label>
								<textarea class="form-control" name="message" rows="8" placeholder="Type your reply here..." required></textarea>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Send Reply</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Creating New Ticket -->
		<div class="modal fade" id="createTicketModal" tabindex="-1" aria-labelledby="createTicketModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST" action="create_ticket.php">
						<div class="modal-header">
							<h5 class="modal-title" id="createTicketModalLabel">Create New Support Ticket</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Select User <span class="text-danger">*</span></label>
										<select class="form-control" name="user_id" required>
											<option value="">Select User</option>
											<?php
											$users_sql = "SELECT id, username, email FROM users ORDER BY username";
											$users_result = mysqli_query($conn, $users_sql);
											while ($user = mysqli_fetch_assoc($users_result)) {
												echo "<option value='{$user['id']}'>{$user['username']} ({$user['email']})</option>";
											}
											?>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Category <span class="text-danger">*</span></label>
										<select class="form-control" name="category" required>
											<option value="technical">Technical Support</option>
											<option value="billing">Billing/Payment</option>
											<option value="account">Account Issues</option>
											<option value="trading">Trading Issues</option>
											<option value="verification">Verification</option>
											<option value="general">General Inquiry</option>
										</select>
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Priority <span class="text-danger">*</span></label>
										<select class="form-control" name="priority" required>
											<option value="low">Low</option>
											<option value="medium">Medium</option>
											<option value="high">High</option>
											<option value="urgent">Urgent</option>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Assign To</label>
										<select class="form-control" name="assign_to">
											<option value="0">Unassigned</option>
											<?php mysqli_data_seek($admins_result, 0); ?>
											<?php while ($admin = mysqli_fetch_assoc($admins_result)): ?>
												<option value="<?php echo $admin['id']; ?>">
													<?php echo $admin['name'] . ' (' . $admin['role'] . ')'; ?>
												</option>
											<?php endwhile; ?>
										</select>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Subject <span class="text-danger">*</span></label>
								<input type="text" class="form-control" name="subject" required placeholder="Enter ticket subject">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Description <span class="text-danger">*</span></label>
								<textarea class="form-control" name="description" rows="6" required placeholder="Describe the issue in detail"></textarea>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Create Ticket</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Deleting Ticket (hidden form) -->
		<form method="POST" id="deleteForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_ticket">
			<input type="hidden" name="ticket_id" id="deleteTicketId">
			<input type="hidden" name="admin_pin" id="deletePin">
		</form>
		
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<!-- DataTables -->
		<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
		<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
		
		<script>
		$(document).ready(function() {
			// Initialize DataTable
			$('#ticketsTable').DataTable({
				"pageLength": 25,
				"order": [[0, 'desc']],
				"language": {
					"search": "Search:",
					"lengthMenu": "Show _MENU_ entries",
					"info": "Showing _START_ to _END_ of _TOTAL_ entries",
					"paginate": {
						"first": "First",
						"last": "Last",
						"next": "Next",
						"previous": "Previous"
					}
				}
			});
			
			// Update Ticket Modal
			$('#updateTicketModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var ticketId = button.data('ticket-id');
				var currentStatus = button.data('current-status');
				var currentPriority = button.data('current-priority');
				var modal = $(this);
				
				modal.find('#updateTicketId').val(ticketId);
				modal.find('select[name="status"]').val(currentStatus);
				modal.find('select[name="priority"]').val(currentPriority);
				modal.find('.modal-title').text('Update Ticket #' + ticketId);
			});
			
			// Reply Modal
			$('#replyModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var ticketId = button.data('ticket-id');
				var modal = $(this);
				
				modal.find('#replyTicketId').val(ticketId);
				modal.find('.modal-title').text('Reply to Ticket #' + ticketId);
			});
			
			// View Ticket Modal
			$('#viewTicketModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var ticketId = button.data('ticket-id');
				var modal = $(this);
				
				// Load ticket details via AJAX
				$.ajax({
					url: 'ajax/get_ticket_details.php',
					type: 'GET',
					data: { ticket_id: ticketId },
					success: function(data) {
						modal.find('#ticketDetails').html(data);
						modal.find('.modal-title').text('Ticket #' + ticketId);
						
						// Store ticket ID for reply function
						modal.find('#replyTicketId').val(ticketId);
					}
				});
			});
		});
		
		// Confirm Delete with PIN
		function confirmDelete(ticketId) {
			Swal.fire({
				title: 'Delete Ticket?',
				html: `
					<p>This action cannot be undone. All ticket data and replies will be permanently deleted.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Delete Ticket',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Submit the delete form
					document.getElementById('deleteTicketId').value = ticketId;
					document.getElementById('deletePin').value = result.value.pin;
					document.getElementById('deleteForm').submit();
				}
			});
		}
		
		// Reply to ticket from view modal
		function replyToTicket() {
			var ticketId = $('#viewTicketModal #replyTicketId').val();
			if (ticketId) {
				$('#viewTicketModal').modal('hide');
				setTimeout(function() {
					$('#replyModal #replyTicketId').val(ticketId);
					$('#replyModal').modal('show');
				}, 500);
			}
		}
		
		// Auto-refresh stats every 30 seconds
		setInterval(function() {
			$.ajax({
				url: 'ajax/get_ticket_stats.php',
				type: 'GET',
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update the stat cards
						$('.bg-gradient-primary .fw-500').text(stats.total);
						$('.bg-gradient-danger .fw-500').text(stats.open);
						$('.bg-gradient-warning .fw-500').text(stats.in_progress);
						$('.bg-gradient-success .fw-500').text(stats.resolved);
						$('.bg-gradient-info .fw-500').text(stats.urgent);
						$('.bg-gradient-dark .fw-500').text(stats.high);
						
						// Show notification only if there are new tickets
						if (stats.new_tickets > 0) {
							Swal.fire({
								toast: true,
								position: 'top-end',
								icon: 'info',
								title: stats.new_tickets + ' new tickets',
								showConfirmButton: false,
								timer: 2000
							});
						}
					}
				}
			});
		}, 30000); // 30 seconds
		
		// Function to refresh ticket table
		function refreshTickets() {
			$.ajax({
				url: 'ajax/get_tickets_table.php',
				type: 'GET',
				data: {
					status: '<?php echo $filter_status; ?>',
					priority: '<?php echo $filter_priority; ?>',
					category: '<?php echo $filter_category; ?>',
					search: '<?php echo $search; ?>',
					assigned_to: '<?php echo $assigned_to; ?>'
				},
				success: function(data) {
					$('#ticketsTable tbody').html(data);
					
					// Re-initialize DataTable
					$('#ticketsTable').DataTable().destroy();
					$('#ticketsTable').DataTable({
						"pageLength": 25,
						"order": [[0, 'desc']]
					});
					
					// Re-attach event listeners
					attachTicketEvents();
				}
			});
		}
		
		// Function to attach event listeners to ticket rows
		function attachTicketEvents() {
			// This function would re-attach all the modal event listeners
			// Implement as needed based on your requirements
		}
		</script>
		
		<style>
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
			cursor: pointer;
		}
		.badge {
			padding: 5px 10px;
			border-radius: 20px;
			font-size: 12px;
			font-weight: 600;
		}
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		.ticket-reply {
			border-left: 3px solid #007bff;
			padding-left: 15px;
			margin-bottom: 15px;
		}
		.ticket-reply.admin {
			border-left-color: #28a745;
			background-color: #f8f9fa;
		}
		.ticket-reply.user {
			border-left-color: #6c757d;
		}
		</style>
		
	</body>
</html>

<?php
// Helper function to show time ago
function time_ago($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return $diff . " seconds";
    } elseif ($diff < 3600) {
        return floor($diff / 60) . " minutes";
    } elseif ($diff < 86400) {
        return floor($diff / 3600) . " hours";
    } elseif ($diff < 604800) {
        return floor($diff / 86400) . " days";
    } elseif ($diff < 2592000) {
        return floor($diff / 604800) . " weeks";
    } elseif ($diff < 31536000) {
        return floor($diff / 2592000) . " months";
    } else {
        return floor($diff / 31536000) . " years";
    }
}
?>