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

// Handle support ticket submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_ticket'])) {
    $ticket_type = $conn->real_escape_string($_POST['ticket_type']);
    $subject = $conn->real_escape_string($_POST['subject']);
    $description = $conn->real_escape_string($_POST['description']);
    $priority = $conn->real_escape_string($_POST['priority']);
    
    $ticket_number = 'TKT' . date('Ymd') . str_pad(rand(0, 999), 3, '0', STR_PAD_LEFT);
    
    $sql = "INSERT INTO support_tickets (user_id, ticket_number, ticket_type, subject, description, priority, status) 
            VALUES ('$user_id', '$ticket_number', '$ticket_type', '$subject', '$description', '$priority', 'open')";
    
    if (mysqli_query($conn, $sql)) {
        $ticket_id = mysqli_insert_id($conn);
        
        // Get user details for notification
        $userQuery = mysqli_query($conn, "SELECT first_name, last_name, email FROM users WHERE id='$user_id'");
        $userData = mysqli_fetch_assoc($userQuery);
        $first_name = $userData['first_name'];
        $last_name = $userData['last_name'];
        $email = $userData['email'];
        
        // Get IP address for security
        $user_ip = $_SERVER['REMOTE_ADDR'];
        
        // NOTIFICATION: Support Ticket Created (USER)
        $mail_subject = "Support Ticket Created - " . $ticket_number;
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                            
                            <p class='message'>
                                ✅ <strong>Your support ticket has been created successfully!</strong><br>
                                We've received your request and will respond as soon as possible.
                            </p>

                            <!-- Ticket Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Ticket Number:</strong> <span style='color: #2F2CD8; font-weight: bold;'>" . $ticket_number . "</span><br>
                                    <strong>Subject:</strong> " . htmlspecialchars($subject) . "<br>
                                    <strong>Type:</strong> " . ucfirst($ticket_type) . "<br>
                                    <strong>Priority:</strong> <span style='color: " . 
                                        ($priority == 'urgent' ? '#dc3545' : 
                                         ($priority == 'high' ? '#ff6b35' : 
                                          ($priority == 'medium' ? '#ffc107' : '#28a745'))) . 
                                        "; font-weight: bold;'>" . ucfirst($priority) . "</span><br>
                                    <strong>Status:</strong> <span style='color: #17a2b8; font-weight: bold;'>Open</span><br>
                                    <strong>Date Submitted:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Submitted From IP:</strong> " . $user_ip . "
                                </div>
                            </div>

                            <!-- Your Message -->
                            <div class='message-section'>
                                <h3 style='color: #2c3e50;'>Your Message</h3>
                                <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 15px 0;'>
                                    <p style='color: #495057; white-space: pre-wrap;'>" . nl2br(htmlspecialchars($description)) . "</p>
                                </div>
                            </div>

                            <!-- What Happens Next -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>What Happens Next?</h3>
                                <p style='color: #6c757d;'>Based on your priority level:</p>
                                <ul style='color: #6c757d;'>
                                    <li><strong>Urgent:</strong> Response within 1 hour</li>
                                    <li><strong>High:</strong> Response within 4 hours</li>
                                    <li><strong>Medium:</strong> Response within 12 hours</li>
                                    <li><strong>Low:</strong> Response within 24 hours</li>
                                </ul>
                                <p style='color: #6c757d;'>You'll receive email updates when we respond.</p>
                            </div>

                            <!-- Action Buttons -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/support/ticket-details.php?id=" . $ticket_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;'>
                                    All Support Tickets
                                </a>
                            </div>

                            <!-- Support Information -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>📞 Need Immediate Assistance?</h4>
                                <p style='color: #0056b3;'>
                                    <strong>Phone:</strong> 086 100 1234<br>
                                    <strong>Live Chat:</strong> Available on our platform<br>
                                    <strong>Business Hours:</strong> Mon-Fri: 8:00-17:00 | Sat: 9:00-13:00
                                </p>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Thank you for contacting " . $sitename . " Support!</p>
                                <p class='support-text'>We're committed to helping you resolve your issue.</p>
                            </div>
                        </div>";

        // Send user notification
        require_once("../proccess/mail_sender.php");

        // NOTIFICATION: New Support Ticket (ADMIN)
        $admin_mail_subject = "New Support Ticket - " . $ticket_number . " [" . ucfirst($priority) . "]";
        $admin_mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>New Support Ticket Received</h2>
                                
                                <p class='message'>
                                    A user has submitted a new support ticket requiring attention.
                                </p>

                                <!-- Ticket Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>Ticket Number:</strong> <span style='color: #198754; font-weight: bold;'>" . $ticket_number . "</span><br>
                                        <strong>Ticket ID:</strong> " . $ticket_id . "<br>
                                        <strong>User ID:</strong> " . $user_id . "<br>
                                        <strong>User Name:</strong> " . $first_name . " " . $last_name . "<br>
                                        <strong>User Email:</strong> " . $email . "<br>
                                        <strong>Ticket Type:</strong> " . ucfirst($ticket_type) . "<br>
                                        <strong>Priority:</strong> <span style='color: " . 
                                            ($priority == 'urgent' ? '#dc3545' : 
                                             ($priority == 'high' ? '#ff6b35' : 
                                              ($priority == 'medium' ? '#ffc107' : '#28a745'))) . 
                                            "; font-weight: bold;'>" . ucfirst($priority) . "</span><br>
                                        <strong>Subject:</strong> " . htmlspecialchars($subject) . "<br>
                                        <strong>Submitted:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>User IP:</strong> " . $user_ip . "<br>
                                        <strong>Status:</strong> <span style='color: #17a2b8; font-weight: bold;'>Open - Awaiting Response</span>
                                    </div>
                                </div>

                                <!-- User's Message -->
                                <div class='message-section'>
                                    <h3 style='color: #2c3e50;'>User's Message</h3>
                                    <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 15px 0;'>
                                        <p style='color: #495057; white-space: pre-wrap;'>" . nl2br(htmlspecialchars($description)) . "</p>
                                    </div>
                                </div>

                                <!-- User Information -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>User Information</h3>
                                    <p style='color: #6c757d;'>
                                        <strong>Account Created:</strong> " . 
                                            (isset($userData['created_at']) ? date('F j, Y', strtotime($userData['created_at'])) : 'N/A') . "<br>
                                        <strong>Total Tickets:</strong> " . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT COUNT(*) as total FROM support_tickets WHERE user_id='$user_id'"))['total'] ?? 0) . "<br>
                                        <strong>Previous Tickets:</strong> " . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT COUNT(*) as closed FROM support_tickets WHERE user_id='$user_id' AND status='resolved'"))['closed'] ?? 0) . " resolved<br>
                                        <strong>Account Status:</strong> " . 
                                            (isset($userData['status']) ? ucfirst($userData['status']) : 'Active')
                                    </p>
                                </div>

                                <!-- SLA Information -->
                                <div style='background: " . 
                                    ($priority == 'urgent' ? '#f8d7da' : 
                                     ($priority == 'high' ? '#fff3cd' : 
                                      ($priority == 'medium' ? '#d1ecf1' : '#d4edda'))) . 
                                    "; border: 1px solid " . 
                                    ($priority == 'urgent' ? '#f5c6cb' : 
                                     ($priority == 'high' ? '#ffeaa7' : 
                                      ($priority == 'medium' ? '#bee5eb' : '#c3e6cb'))) . 
                                    "; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: " . 
                                        ($priority == 'urgent' ? '#721c24' : 
                                         ($priority == 'high' ? '#856404' : 
                                          ($priority == 'medium' ? '#0c5460' : '#155724'))) . 
                                        ";'>⏰ SLA REQUIREMENT</h4>
                                    <p style='color: " . 
                                        ($priority == 'urgent' ? '#721c24' : 
                                         ($priority == 'high' ? '#856404' : 
                                          ($priority == 'medium' ? '#0c5460' : '#155724'))) . 
                                        ";'>
                                        <strong>Priority: " . ucfirst($priority) . "</strong><br>
                                        " . ($priority == 'urgent' ? 
                                            'Response required: WITHIN 1 HOUR' : 
                                            ($priority == 'high' ? 
                                             'Response required: WITHIN 4 HOURS' : 
                                             ($priority == 'medium' ? 
                                              'Response required: WITHIN 12 HOURS' : 
                                              'Response required: WITHIN 24 HOURS'))) . "<br>
                                        Current time: " . date('g:i A') . "
                                    </p>
                                </div>

                                <!-- Admin Actions -->
                                <div style='text-align: center; margin: 30px 0;'>
                                    <a href='" . $myUrl . "/admin/support/ticket.php?id=" . $ticket_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;'>
                                        Respond to Ticket
                                    </a>
                                    <a href='" . $myUrl . "/admin/users.php?id=" . $user_id . "' 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 User Profile
                                    </a>
                                </div>

                                <!-- Auto-Assign Info -->
                                <div class='support-section'>
                                    <p class='support-text'>Ticket assigned to: <strong>Unassigned</strong></p>
                                    <a href='" . $myUrl . "/admin/support/assign-ticket.php?id=" . $ticket_id . "' class='support-link'>Assign to Support Agent</a>
                                </div>
                            </div>";

        // Send admin notification
        require_once("../proccess/admin_mailer.php");

        $ticket_success = "Support ticket submitted successfully! Your ticket number is: <strong>" . $ticket_number . "</strong>. You will receive a confirmation email.";
    } else {
        $ticket_error = "Failed to submit ticket: " . mysqli_error($conn);
    }
}

// Handle feedback submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_feedback'])) {
    $feedback_type = $conn->real_escape_string($_POST['feedback_type']);
    $rating = $conn->real_escape_string($_POST['rating']);
    $comments = $conn->real_escape_string($_POST['comments']);
    $suggestions = $conn->real_escape_string($_POST['suggestions']);
    
    // Get user details for notification
    $userQuery = mysqli_query($conn, "SELECT first_name, last_name, email FROM users WHERE id='$user_id'");
    $userData = mysqli_fetch_assoc($userQuery);
    $first_name = $userData['first_name'];
    $last_name = $userData['last_name'];
    $email = $userData['email'];
    
    $sql = "INSERT INTO user_feedback (user_id, feedback_type, rating, comments, suggestions, status) 
            VALUES ('$user_id', '$feedback_type', '$rating', '$comments', '$suggestions', 'new')";
    
    if (mysqli_query($conn, $sql)) {
        $feedback_id = mysqli_insert_id($conn);
        
        // NOTIFICATION: Feedback Submitted (USER)
        $mail_subject = "Thank You for Your Feedback";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                            
                            <p class='message'>
                                🙏 <strong>Thank you for sharing your feedback with " . $sitename . "!</strong><br>
                                We truly value your input and will use it to improve our services.
                            </p>

                            <!-- Feedback Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Feedback Reference:</strong> FDB-" . $feedback_id . "<br>
                                    <strong>Feedback Type:</strong> " . ucwords(str_replace('_', ' ', $feedback_type)) . "<br>
                                    <strong>Rating:</strong> " . str_repeat('★', $rating) . str_repeat('☆', 5 - $rating) . " (" . $rating . "/5)<br>
                                    <strong>Submitted:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Status:</strong> <span style='color: #17a2b8; font-weight: bold;'>Received - Under Review</span>
                                </div>
                            </div>

                            <!-- Your Comments -->
                            " . (!empty($comments) ? "
                            <div class='message-section'>
                                <h3 style='color: #2c3e50;'>Your Comments</h3>
                                <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 15px 0;'>
                                    <p style='color: #495057; white-space: pre-wrap;'>" . nl2br(htmlspecialchars($comments)) . "</p>
                                </div>
                            </div>" : "") . "

                            <!-- Your Suggestions -->
                            " . (!empty($suggestions) ? "
                            <div class='message-section'>
                                <h3 style='color: #2c3e50;'>Your Suggestions</h3>
                                <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 15px 0;'>
                                    <p style='color: #495057; white-space: pre-wrap;'>" . nl2br(htmlspecialchars($suggestions)) . "</p>
                                </div>
                            </div>" : "") . "

                            <!-- How We Use Feedback -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>💡 How We Use Your Feedback</h4>
                                <p style='color: #0056b3;'>
                                    • Improve our website and application process<br>
                                    • Enhance customer service quality<br>
                                    • Develop better loan products<br>
                                    • Identify and fix technical issues<br>
                                    • Train our support team
                                </p>
                            </div>

                            <!-- What Happens Next -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>What Happens Next?</h3>
                                <p style='color: #6c757d;'>
                                    1. Our team reviews all feedback weekly<br>
                                    2. High-priority issues are addressed immediately<br>
                                    3. Suggestions are discussed in team meetings<br>
                                    4. We implement changes based on user feedback<br>
                                    5. You may see improvements in future updates
                                </p>
                            </div>

                            <!-- Action Button -->
                            <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;'>
                                    Visit Help Center
                                </a>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Your feedback helps us serve you better!</p>
                                <p class='support-text'>Thank you for being a valued " . $sitename . " customer.</p>
                            </div>
                        </div>";

        // Send user notification
        require_once("../proccess/mail_sender.php");

        // NOTIFICATION: Feedback Received (ADMIN)
        $admin_mail_subject = "New User Feedback - Rating: " . $rating . "/5";
        $admin_mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>New User Feedback Received</h2>
                                
                                <p class='message'>
                                    A user has submitted feedback about our services.
                                </p>

                                <!-- Feedback Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>Feedback ID:</strong> FDB-" . $feedback_id . "<br>
                                        <strong>User ID:</strong> " . $user_id . "<br>
                                        <strong>User Name:</strong> " . $first_name . " " . $last_name . "<br>
                                        <strong>User Email:</strong> " . $email . "<br>
                                        <strong>Feedback Type:</strong> " . ucwords(str_replace('_', ' ', $feedback_type)) . "<br>
                                        <strong>Rating:</strong> " . str_repeat('★', $rating) . str_repeat('☆', 5 - $rating) . " (" . $rating . "/5)<br>
                                        <strong>Submitted:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>Status:</strong> <span style='color: #17a2b8; font-weight: bold;'>New - Pending Review</span>
                                    </div>
                                </div>

                                <!-- User Comments -->
                                " . (!empty($comments) ? "
                                <div class='message-section'>
                                    <h3 style='color: #2c3e50;'>User Comments</h3>
                                    <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 15px 0;'>
                                        <p style='color: #495057; white-space: pre-wrap;'>" . nl2br(htmlspecialchars($comments)) . "</p>
                                    </div>
                                </div>" : "<p style='color: #6c757d;'>No comments provided.</p>") . "

                                <!-- User Suggestions -->
                                " . (!empty($suggestions) ? "
                                <div class='message-section'>
                                    <h3 style='color: #2c3e50;'>User Suggestions</h3>
                                    <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 15px 0;'>
                                        <p style='color: #495057; white-space: pre-wrap;'>" . nl2br(htmlspecialchars($suggestions)) . "</p>
                                    </div>
                                </div>" : "<p style='color: #6c757d;'>No suggestions provided.</p>") . "

                                <!-- User Feedback History -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>User Feedback History</h3>
                                    <p style='color: #6c757d;'>
                                        <strong>Total Feedback Submissions:</strong> " . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT COUNT(*) as total FROM user_feedback WHERE user_id='$user_id'"))['total'] ?? 1) . "<br>
                                        <strong>Average Rating:</strong> " . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT AVG(rating) as avg_rating FROM user_feedback WHERE user_id='$user_id'"))['avg_rating'] ?? $rating) . "/5<br>
                                        <strong>Last Feedback:</strong> " . 
                                            (mysqli_fetch_assoc(mysqli_query($conn, 
                                                "SELECT created_at FROM user_feedback WHERE user_id='$user_id' ORDER BY id DESC LIMIT 1,1"))['created_at'] ?? 'First feedback')
                                    </p>
                                </div>

                                <!-- Admin Actions -->
                                <div style='text-align: center; margin: 30px 0;'>
                                    <a href='" . $myUrl . "/admin/feedback/view.php?id=" . $feedback_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;'>
                                        Review Feedback
                                    </a>
                                    <a href='" . $myUrl . "/admin/users.php?id=" . $user_id . "' 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 User Profile
                                    </a>
                                </div>

                                <!-- Priority Indicator -->
                                <div style='background: " . 
                                    ($rating <= 2 ? '#f8d7da' : 
                                     ($rating == 3 ? '#fff3cd' : '#d4edda')) . 
                                    "; border: 1px solid " . 
                                    ($rating <= 2 ? '#f5c6cb' : 
                                     ($rating == 3 ? '#ffeaa7' : '#c3e6cb')) . 
                                    "; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: " . 
                                        ($rating <= 2 ? '#721c24' : 
                                         ($rating == 3 ? '#856404' : '#155724')) . 
                                        ";'>" . 
                                        ($rating <= 2 ? '🚨 URGENT REVIEW NEEDED' : 
                                         ($rating == 3 ? '⚠️ REVIEW RECOMMENDED' : '✅ STANDARD REVIEW')) . "</h4>
                                    <p style='color: " . 
                                        ($rating <= 2 ? '#721c24' : 
                                         ($rating == 3 ? '#856404' : '#155724')) . 
                                        ";'>
                                        <strong>Rating: " . $rating . "/5</strong><br>
                                        " . ($rating <= 2 ? 
                                            'Low rating indicates user dissatisfaction. Immediate review recommended.' : 
                                            ($rating == 3 ? 
                                             'Average rating suggests room for improvement. Review within 48 hours.' : 
                                             'Positive rating. Standard review process applies.')) . "
                                    </p>
                                </div>
                            </div>";

        // Send admin notification
        require_once("../proccess/admin_mailer.php");

        $feedback_success = "Thank you for your feedback! We appreciate your input.";
    } else {
        $feedback_error = "Failed to submit feedback: " . mysqli_error($conn);
    }
}

// Create support_tickets table if not exists
$create_tickets_table = "
CREATE TABLE IF NOT EXISTS support_tickets (
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    user_id INT(11) NOT NULL,
    ticket_number VARCHAR(20) UNIQUE NOT NULL,
    ticket_type VARCHAR(50) NOT NULL,
    subject VARCHAR(255) NOT NULL,
    description TEXT NOT NULL,
    priority ENUM('low','medium','high','urgent') DEFAULT 'medium',
    status ENUM('open','in_progress','resolved','closed') DEFAULT 'open',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
)";

// Create user_feedback table if not exists
$create_feedback_table = "
CREATE TABLE IF NOT EXISTS user_feedback (
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    user_id INT(11) NOT NULL,
    feedback_type VARCHAR(50) NOT NULL,
    rating INT(1) NOT NULL,
    comments TEXT,
    suggestions TEXT,
    status ENUM('new','reviewed','actioned') DEFAULT 'new',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
)";

mysqli_query($conn, $create_tickets_table);
mysqli_query($conn, $create_feedback_table);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Help Center - E-Finance Loans</title>
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
    .support-card {
        transition: transform 0.2s ease;
        border: none;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .support-card:hover {
        transform: translateY(-5px);
    }
    .faq-item {
        border-bottom: 1px solid #eee;
        padding: 15px 0;
    }
    .faq-question {
        font-weight: 600;
        cursor: pointer;
        padding: 10px 0;
    }
    .faq-answer {
        padding: 10px 0;
        display: none;
    }
    .contact-method {
        text-align: center;
        padding: 30px 20px;
        border-radius: 10px;
        transition: all 0.3s ease;
    }
    .contact-method:hover {
        background: #f8f9fa;
        transform: scale(1.05);
    }
    .rating-stars {
        font-size: 24px;
        color: #ffc107;
        cursor: pointer;
    }
    .chat-bubble {
        max-width: 70%;
        padding: 12px 16px;
        border-radius: 18px;
        margin: 10px 0;
    }
    .chat-bubble.user {
        background: #007bff;
        color: white;
        margin-left: auto;
    }
    .chat-bubble.support {
        background: #f1f1f1;
        color: #333;
    }
    </style>
</head>
<body class="dashboard">
    <div id="main-wrapper">
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>

        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>Help & Support Center</h3>
                                        <p class="mb-2">We're here to help you with any questions or issues</p>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <div class="breadcrumbs">
                                        <a href="dashboard.php">Home</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">Help Center</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- QUICK SUPPORT OPTIONS -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="card support-card">
                            <div class="card-body">
                                <h5 class="card-title mb-4">Quick Support Options</h5>
                                <div class="row g-4">
                                    <div class="col-md-3">
                                        <div class="contact-method">
                                            <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px;">
                                                <i class="fi fi-rr-phone-call text-primary fs-2"></i>
                                            </div>
                                            <h6>Call Support</h6>
                                            <p class="text-muted small mb-2">Speak directly with our team</p>
                                            <a href="tel:+27 73 37411067" class="btn btn-outline-primary btn-sm">+27 73 374 1106</a>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="contact-method">
                                            <div class="bg-success bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px;">
                                                <i class="fi fi-rr-envelope text-success fs-2"></i>
                                            </div>
                                            <h6>Email Us</h6>
                                            <p class="text-muted small mb-2">Send us a detailed message</p>
                                            <a href="mailto:info@efina.co.za" class="btn btn-outline-success btn-sm">info@efina.co.za</a>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="contact-method">
                                            <div class="bg-info bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px;">
                                                <i class="fi fi-rr-comments text-info fs-2"></i>
                                            </div>
                                            <h6>Live Chat</h6>
                                            <p class="text-muted small mb-2">Instant messaging support</p>
                                            <button class="btn btn-outline-info btn-sm" onclick="openLiveChat()">Start Chat</button>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="contact-method">
                                            <div class="bg-warning bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px;">
                                                <i class="fi fi-rr-document text-warning fs-2"></i>
                                            </div>
                                            <h6>Submit Ticket</h6>
                                            <p class="text-muted small mb-2">Track your support requests</p>
                                            <button class="btn btn-outline-warning btn-sm" data-bs-toggle="modal" data-bs-target="#supportTicketModal">Create Ticket</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <!-- FAQS & GUIDES -->
                    <div class="col-xl-8">
                        <div class="card support-card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Frequently Asked Questions</h5>
                            </div>
                            <div class="card-body">
                                <!-- Search FAQs -->
                                <div class="mb-4">
                                    <input type="text" class="form-control" placeholder="Search FAQs..." id="faqSearch">
                                </div>

                                <!-- FAQ Categories -->
                                <div class="mb-4">
                                    <div class="btn-group w-100" role="group">
                                        <button type="button" class="btn btn-outline-primary active" data-category="all">All Questions</button>
                                        <button type="button" class="btn btn-outline-primary" data-category="application">Application</button>
                                        <button type="button" class="btn btn-outline-primary" data-category="repayment">Repayment</button>
                                        <button type="button" class="btn btn-outline-primary" data-category="documents">Documents</button>
                                        <button type="button" class="btn btn-outline-primary" data-category="technical">Technical</button>
                                    </div>
                                </div>

                                <!-- FAQ Items -->
                                <div class="faq-container">
                                    <!-- Application FAQs -->
                                    <div class="faq-category" data-category="application">
                                        <h6 class="text-primary mb-3">📝 Application Questions</h6>
                                        
                                        <div class="faq-item">
                                            <div class="faq-question" onclick="toggleFAQ(this)">
                                                How long does loan approval take?
                                            </div>
                                            <div class="faq-answer">
                                                Most loan applications are processed within 24-48 hours. However, during peak periods or if additional verification is required, it may take up to 3 business days. You'll receive SMS and email notifications at each stage.
                                            </div>
                                        </div>

                                        <div class="faq-item">
                                            <div class="faq-question" onclick="toggleFAQ(this)">
                                                What documents do I need to apply?
                                            </div>
                                            <div class="faq-answer">
                                                You'll need:<br>
                                                • South African ID document<br>
                                                • Latest 3 months bank statements<br>
                                                • Latest payslip or proof of income<br>
                                                • Proof of residence (not older than 3 months)<br>
                                                All documents must be clear and readable.
                                            </div>
                                        </div>

                                        <div class="faq-item">
                                            <div class="faq-question" onclick="toggleFAQ(this)">
                                                What are the eligibility requirements?
                                            </div>
                                            <div class="faq-answer">
                                                To qualify for a loan, you must:<br>
                                                • Be a South African citizen or permanent resident<br>
                                                • Be 18 years or older<br>
                                                • Have a minimum monthly income of R5,000<br>
                                                • Have a valid bank account<br>
                                                • Pass our credit assessment
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Repayment FAQs -->
                                    <div class="faq-category" data-category="repayment">
                                        <h6 class="text-success mb-3">💰 Repayment Questions</h6>
                                        
                                        <div class="faq-item">
                                            <div class="faq-question" onclick="toggleFAQ(this)">
                                                Can I pay off my loan early?
                                            </div>
                                            <div class="faq-answer">
                                                Yes! You can pay off your loan early without any penalties. Early settlement may even reduce your total interest payable. Contact our support team to arrange early settlement.
                                            </div>
                                        </div>

                                        <div class="faq-item">
                                            <div class="faq-question" onclick="toggleFAQ(this)">
                                                What happens if I miss a payment?
                                            </div>
                                            <div class="faq-answer">
                                                If you miss a payment:<br>
                                                • A R150 late payment fee will be charged<br>
                                                • Your credit score may be affected<br>
                                                • We'll contact you to arrange payment<br>
                                                • Persistent non-payment may lead to legal action<br>
                                                Please contact us immediately if you're struggling to make payments.
                                            </div>
                                        </div>

                                        <div class="faq-item">
                                            <div class="faq-question" onclick="toggleFAQ(this)">
                                                How can I change my payment date?
                                            </div>
                                            <div class="faq-answer">
                                                You can request to change your payment date once per loan term. Contact our support team at least 5 business days before your next payment date. A small administrative fee of R50 may apply.
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Documents FAQs -->
                                    <div class="faq-category" data-category="documents">
                                        <h6 class="text-warning mb-3">📄 Document Questions</h6>
                                        
                                        <div class="faq-item">
                                            <div class="faq-question" onclick="toggleFAQ(this)">
                                                What proof of residence is acceptable?
                                            </div>
                                            <div class="faq-answer">
                                                Acceptable proof of residence includes:<br>
                                                • Utility bill (electricity, water)<br>
                                                • Municipal rates bill<br>
                                                • Lease agreement<br>
                                                • Bank statement<br>
                                                • Retail account statement<br>
                                                The document must be less than 3 months old and show your name and physical address.
                                            </div>
                                        </div>

                                        <div class="faq-item">
                                            <div class="faq-question" onclick="toggleFAQ(this)">
                                                My documents were rejected. What now?
                                            </div>
                                            <div class="faq-answer">
                                                Common reasons for document rejection:<br>
                                                • Blurry or unreadable images<br>
                                                • Documents older than 3 months<br>
                                                • Missing pages or information<br>
                                                • Incorrect document type<br>
                                                Please upload clear, color copies of all required documents. If issues persist, contact our support team.
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Technical FAQs -->
                                    <div class="faq-category" data-category="technical">
                                        <h6 class="text-info mb-3">🔧 Technical Questions</h6>
                                        
                                        <div class="faq-item">
                                            <div class="faq-question" onclick="toggleFAQ(this)">
                                                I can't login to my account. What should I do?
                                            </div>
                                            <div class="faq-answer">
                                                If you're having login issues:<br>
                                                1. Click "Forgot Password" to reset your password<br>
                                                2. Ensure you're using the correct username/email<br>
                                                3. Clear your browser cache and cookies<br>
                                                4. Try using a different browser<br>
                                                5. Contact support if issues persist
                                            </div>
                                        </div>

                                        <div class="faq-item">
                                            <div class="faq-question" onclick="toggleFAQ(this)">
                                                The website is not working properly.
                                            </div>
                                            <div class="faq-answer">
                                                Technical issues can usually be resolved by:<br>
                                                • Refreshing the page<br>
                                                • Clearing browser cache<br>
                                                • Trying a different browser<br>
                                                • Checking your internet connection<br>
                                                If problems continue, please report the issue using our support ticket system with details of what you were trying to do.
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- LOAN DISPUTE REPORTING -->
                        <div class="card support-card mt-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Loan Dispute Reporting</h5>
                            </div>
                            <div class="card-body">
                                <div class="alert alert-warning">
                                    <i class="fi fi-rr-shield-exclamation me-2"></i>
                                    <strong>Important:</strong> If you have a dispute regarding your loan, please follow the proper channels as required by the National Credit Act.
                                </div>

                                <div class="row g-4">
                                    <div class="col-md-6">
                                        <div class="card border-danger">
                                            <div class="card-body text-center">
                                                <i class="fi fi-rr-scale-balanced text-danger fs-1 mb-3"></i>
                                                <h6>Internal Dispute Resolution</h6>
                                                <p class="small text-muted">Submit your complaint through our internal process first</p>
                                                <button class="btn btn-outline-danger btn-sm" data-bs-toggle="modal" data-bs-target="#disputeModal">
                                                    Submit Complaint
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="card border-warning">
                                            <div class="card-body text-center">
                                                <i class="fi fi-rr-gavel text-warning fs-1 mb-3"></i>
                                                <h6>External Resolution</h6>
                                                <p class="small text-muted">If unsatisfied, contact the National Credit Regulator</p>
                                                <a href="https://www.ncr.org.za" target="_blank" class="btn btn-outline-warning btn-sm">
                                                    Contact NCR
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="mt-4">
                                    <h6>Dispute Resolution Process</h6>
                                    <ol class="small">
                                        <li><strong>Step 1:</strong> Submit your complaint through our internal system</li>
                                        <li><strong>Step 2:</strong> We will acknowledge receipt within 2 business days</li>
                                        <li><strong>Step 3:</strong> Investigation and response within 15 business days</li>
                                        <li><strong>Step 4:</strong> If unsatisfied, escalate to NCR within 6 months</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- FEEDBACK & QUICK HELP -->
                    <div class="col-xl-4">
                        <!-- FEEDBACK FORM -->
                        <div class="card support-card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Share Your Feedback</h5>
                            </div>
                            <div class="card-body">
                                <?php if(isset($feedback_success)): ?>
                                    <div class="alert alert-success"><?php echo $feedback_success; ?></div>
                                <?php endif; ?>
                                <?php if(isset($feedback_error)): ?>
                                    <div class="alert alert-danger"><?php echo $feedback_error; ?></div>
                                <?php endif; ?>

                                <form method="POST">
                                    <div class="mb-3">
                                        <label class="form-label">Feedback Type</label>
                                        <select class="form-select" name="feedback_type" required>
                                            <option value="">Select type</option>
                                            <option value="website">Website Experience</option>
                                            <option value="application">Loan Application</option>
                                            <option value="service">Customer Service</option>
                                            <option value="product">Loan Products</option>
                                            <option value="technical">Technical Issue</option>
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Rating</label>
                                        <div class="rating-stars mb-2">
                                            <?php for($i = 1; $i <= 5; $i++): ?>
                                                <span class="star" data-rating="<?php echo $i; ?>" onclick="setRating(<?php echo $i; ?>)">☆</span>
                                            <?php endfor; ?>
                                        </div>
                                        <input type="hidden" name="rating" id="ratingValue" required>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Comments</label>
                                        <textarea class="form-control" name="comments" rows="3" placeholder="Tell us about your experience..."></textarea>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Suggestions for Improvement</label>
                                        <textarea class="form-control" name="suggestions" rows="2" placeholder="Any suggestions to make us better?"></textarea>
                                    </div>

                                    <button type="submit" name="submit_feedback" class="btn btn-primary w-100">
                                        Submit Feedback
                                    </button>
                                </form>
                            </div>
                        </div>

                        <!-- QUICK HELP GUIDES -->
                        <div class="card support-card mt-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Quick Help Guides</h5>
                            </div>
                            <div class="card-body">
                                <div class="list-group list-group-flush">
                                    <a href="#" class="list-group-item list-group-item-action d-flex align-items-center">
                                        <i class="fi fi-rr-document me-3 text-primary"></i>
                                        <div>
                                            <div class="fw-medium">How to Apply for a Loan</div>
                                            <small class="text-muted">Step-by-step guide</small>
                                        </div>
                                    </a>
                                    <a href="#" class="list-group-item list-group-item-action d-flex align-items-center">
                                        <i class="fi fi-rr-credit-card me-3 text-success"></i>
                                        <div>
                                            <div class="fw-medium">Making Payments</div>
                                            <small class="text-muted">Payment methods and schedules</small>
                                        </div>
                                    </a>
                                    <a href="#" class="list-group-item list-group-item-action d-flex align-items-center">
                                        <i class="fi fi-rr-user me-3 text-info"></i>
                                        <div>
                                            <div class="fw-medium">Updating Your Profile</div>
                                            <small class="text-muted">Manage your personal information</small>
                                        </div>
                                    </a>
                                    <a href="#" class="list-group-item list-group-item-action d-flex align-items-center">
                                        <i class="fi fi-rr-shield me-3 text-warning"></i>
                                        <div>
                                            <div class="fw-medium">Security Tips</div>
                                            <small class="text-muted">Protecting your account</small>
                                        </div>
                                    </a>
                                </div>
                            </div>
                        </div>

                        <!-- CONTACT INFORMATION -->
                        <div class="card support-card mt-4">
                            <div class="card-body">
                                <h6 class="card-title">Contact Information</h6>
                                <div class="mb-3">
                                    <strong>Customer Support</strong><br>
                                    <small class="text-muted">Mon-Fri: 8:00-17:00 | Sat: 9:00-13:00</small>
                                </div>
                                <div class="mb-2">
                                    <i class="fi fi-rr-phone me-2 text-primary"></i>
                                    <span>086 100 1234</span>
                                </div>
                                <div class="mb-2">
                                    <i class="fi fi-rr-envelope me-2 text-success"></i>
                                    <span>info@efina.co.za</span>
                                </div>
                                <div class="mb-2">
                                    <i class="fi fi-rr-marker me-2 text-danger"></i>
                                    <span>123 Finance Street, Johannesburg</span>
                                </div>
                                <div>
                                    <i class="fi fi-rr-globe me-2 text-info"></i>
                                    <span>www.E-Financeloans.co.za</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include('includes/footer.php');?>

    <!-- SUPPORT TICKET MODAL -->
    <div class="modal fade" id="supportTicketModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Submit Support Ticket</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <?php if(isset($ticket_success)): ?>
                        <div class="alert alert-success"><?php echo $ticket_success; ?></div>
                    <?php endif; ?>
                    <?php if(isset($ticket_error)): ?>
                        <div class="alert alert-danger"><?php echo $ticket_error; ?></div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Ticket Type</label>
                                <select class="form-select" name="ticket_type" required>
                                    <option value="">Select type</option>
                                    <option value="technical">Technical Issue</option>
                                    <option value="application">Loan Application</option>
                                    <option value="repayment">Repayment Issue</option>
                                    <option value="document">Document Problem</option>
                                    <option value="account">Account Access</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Priority</label>
                                <select class="form-select" name="priority" required>
                                    <option value="medium">Medium</option>
                                    <option value="low">Low</option>
                                    <option value="high">High</option>
                                    <option value="urgent">Urgent</option>
                                </select>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Subject</label>
                                <input type="text" class="form-control" name="subject" placeholder="Brief description of your issue" required>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Description</label>
                                <textarea class="form-control" name="description" rows="5" placeholder="Please provide detailed information about your issue..." required></textarea>
                            </div>
                        </div>
                        <div class="mt-4">
                            <button type="submit" name="submit_ticket" class="btn btn-primary">Submit Ticket</button>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- DISPUTE MODAL -->
    <div class="modal fade" id="disputeModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Submit Loan Dispute</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fi fi-rr-info me-2"></i>
                        Please provide detailed information about your dispute. We are committed to resolving complaints fairly and in accordance with the National Credit Act.
                    </div>
                    
                    <form>
                        <div class="mb-3">
                            <label class="form-label">Dispute Type</label>
                            <select class="form-select" required>
                                <option value="">Select dispute type</option>
                                <option value="incorrect_charges">Incorrect Charges/Fees</option>
                                <option value="payment_issues">Payment Processing Issues</option>
                                <option value="service_quality">Poor Service Quality</option>
                                <option value="contract_terms">Contract Terms Dispute</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Loan Account Number</label>
                            <input type="text" class="form-control" placeholder="Enter your loan account number" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Detailed Description</label>
                            <textarea class="form-control" rows="5" placeholder="Please provide a detailed description of your dispute, including dates, amounts, and any relevant information..." required></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Desired Resolution</label>
                            <textarea class="form-control" rows="3" placeholder="What would you like us to do to resolve this matter?" required></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Supporting Documents</label>
                            <input type="file" class="form-control" multiple accept=".jpg,.jpeg,.png,.pdf">
                            <small class="text-muted">You can upload screenshots, statements, or other supporting documents (max 5MB each)</small>
                        </div>
                        
                        <div class="alert alert-warning">
                            <small>
                                <strong>Note:</strong> By submitting this dispute, you acknowledge that we will investigate your complaint and respond within 15 business days as required by the National Credit Act.
                            </small>
                        </div>
                        
                        <button type="submit" class="btn btn-warning">Submit Dispute</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- LIVE CHAT WIDGET -->
    <div id="liveChatWidget" style="display: none; position: fixed; bottom: 20px; right: 20px; width: 350px; background: white; border-radius: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.2); z-index: 1000;">
        <div class="card">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h6 class="mb-0">Live Chat Support</h6>
                <button type="button" class="btn-close btn-close-white" onclick="closeLiveChat()"></button>
            </div>
            <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                <div class="chat-messages">
                    <div class="chat-bubble support">
                        <strong>Support Agent:</strong> Hello! Thank you for contacting E-Finance Loans support. How can I help you today?
                    </div>
                </div>
            </div>
            <div class="card-footer">
                <div class="input-group">
                    <input type="text" class="form-control" placeholder="Type your message..." id="chatMessage">
                    <button class="btn btn-primary" onclick="sendChatMessage()">
                        <i class="fi fi-rr-paper-plane"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
    // FAQ functionality
    function toggleFAQ(element) {
        const answer = element.nextElementSibling;
        const isVisible = answer.style.display === 'block';
        
        // Close all answers
        document.querySelectorAll('.faq-answer').forEach(ans => {
            ans.style.display = 'none';
        });
        
        // Toggle current answer
        answer.style.display = isVisible ? 'none' : 'block';
    }

    // FAQ search and filter
    document.getElementById('faqSearch').addEventListener('input', function(e) {
        const searchTerm = e.target.value.toLowerCase();
        const faqItems = document.querySelectorAll('.faq-item');
        
        faqItems.forEach(item => {
            const question = item.querySelector('.faq-question').textContent.toLowerCase();
            const answer = item.querySelector('.faq-answer').textContent.toLowerCase();
            
            if (question.includes(searchTerm) || answer.includes(searchTerm)) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    });

    // FAQ category filter
    document.querySelectorAll('[data-category]').forEach(button => {
        button.addEventListener('click', function() {
            const category = this.getAttribute('data-category');
            
            // Update active button
            document.querySelectorAll('[data-category]').forEach(btn => {
                btn.classList.remove('active');
            });
            this.classList.add('active');
            
            // Show/hide categories
            document.querySelectorAll('.faq-category').forEach(cat => {
                if (category === 'all' || cat.getAttribute('data-category') === category) {
                    cat.style.display = 'block';
                } else {
                    cat.style.display = 'none';
                }
            });
        });
    });

    // Rating stars
    function setRating(rating) {
        const stars = document.querySelectorAll('.star');
        stars.forEach((star, index) => {
            if (index < rating) {
                star.textContent = '★';
                star.style.color = '#ffc107';
            } else {
                star.textContent = '☆';
                star.style.color = '#ffc107';
            }
        });
        document.getElementById('ratingValue').value = rating;
    }

    // Live chat functionality
    function openLiveChat() {
        document.getElementById('liveChatWidget').style.display = 'block';
    }

    function closeLiveChat() {
        document.getElementById('liveChatWidget').style.display = 'none';
    }

    function sendChatMessage() {
        const messageInput = document.getElementById('chatMessage');
        const message = messageInput.value.trim();
        
        if (message) {
            const chatMessages = document.querySelector('.chat-messages');
            
            // Add user message
            const userBubble = document.createElement('div');
            userBubble.className = 'chat-bubble user';
            userBubble.innerHTML = `<strong>You:</strong> ${message}`;
            chatMessages.appendChild(userBubble);
            
            // Clear input
            messageInput.value = '';
            
            // Simulate support response
            setTimeout(() => {
                const supportBubble = document.createElement('div');
                supportBubble.className = 'chat-bubble support';
                supportBubble.innerHTML = `<strong>Support Agent:</strong> Thank you for your message. Our support team will respond shortly. For urgent matters, please call 086 100 1234.`;
                chatMessages.appendChild(supportBubble);
                
                // Scroll to bottom
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }, 1000);
            
            // Scroll to bottom
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
    }

    // Enter key for chat
    document.getElementById('chatMessage').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendChatMessage();
        }
    });

    // Initialize rating stars
    document.querySelectorAll('.star').forEach(star => {
        star.addEventListener('mouseover', function() {
            const rating = this.getAttribute('data-rating');
            setRating(rating);
        });
    });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>