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

// Generate ticket number
function generateTicketNumber() {
    return 'TKT-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $ticket_number = generateTicketNumber();
    $subject = $conn->real_escape_string($_POST['subject']);
    $category = $conn->real_escape_string($_POST['category']);
    $priority = $conn->real_escape_string($_POST['priority']);
    $description = $conn->real_escape_string($_POST['description']);
    
    // 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'];
    
    // Validate required fields
    if (empty($subject) || empty($category) || empty($description)) { ?>
        <script>
            Swal.fire({
                title: 'All Fields Required',
                text: 'Please fill in all required fields.',
                icon: 'error',
                background: '#ffffff',
                color: '#000000',
                iconColor: '#28a745',
                confirmButtonColor: '#3085d6'
            });
        </script>
    <?php
    } else {
        $sql = "INSERT INTO support_tickets (user_id, ticket_number, subject, category, priority, description) 
                VALUES ('$user_id', '$ticket_number', '$subject', '$category', '$priority', '$description')";
        
        if (mysqli_query($conn, $sql)) {
            $ticket_id = mysqli_insert_id($conn);
            
            // 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'>
                                    Thank you for contacting our support team. We have received your support 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>Category:</strong> " . htmlspecialchars($category) . "<br>
                                        <strong>Priority:</strong> <span style='color: " . 
                                            ($priority == 'high' ? '#dc3545' : 
                                             ($priority == 'medium' ? '#ffc107' : '#28a745')) . 
                                            "; font-weight: bold;'>" . ucfirst($priority) . "</span><br>
                                        <strong>Date Submitted:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>Ticket Status:</strong> <span style='color: #17a2b8; font-weight: bold;'>Open</span>
                                    </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;'>Here's what you can expect:</p>
                                    <ul style='color: #6c757d;'>
                                        <li>Our support team will review your ticket within 24 hours</li>
                                        <li>You'll receive email updates when we respond</li>
                                        <li>You can track progress in your dashboard</li>
                                        <li>Average response time: 2-4 hours (business hours)</li>
                                    </ul>
                                </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;'>
                                        View All 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>Live Chat:</strong> Available 24/7 on our platform<br>
                                        <strong>Email:</strong> support@" . parse_url($myUrl, PHP_URL_HOST) . "<br>
                                        <strong>Response Time:</strong> Typically within 1-2 hours during business hours
                                    </p>
                                </div>

                                <!-- Support Section -->
                                <div class='support-section'>
                                    <p class='support-text'>Thank you for choosing " . $sitename . "!</p>
                                    <p class='support-text'>We're committed to providing you with the best support experience.</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;
            $admin_mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>New Support Ticket Created</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>User ID:</strong> " . $user_id . "<br>
                                            <strong>User Name:</strong> " . $first_name . " " . $last_name . "<br>
                                            <strong>User Email:</strong> " . $email . "<br>
                                            <strong>Subject:</strong> " . htmlspecialchars($subject) . "<br>
                                            <strong>Category:</strong> " . htmlspecialchars($category) . "<br>
                                            <strong>Priority:</strong> <span style='color: " . 
                                                ($priority == 'high' ? '#dc3545' : 
                                                 ($priority == 'medium' ? '#ffc107' : '#28a745')) . 
                                                "; font-weight: bold;'>" . ucfirst($priority) . "</span><br>
                                            <strong>Date Submitted:</strong> " . date('F j, Y g:i A') . "<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>Active Bots:</strong> " . 
                                                (mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM user_bot_subscriptions WHERE user_id='$user_id' AND status='active'"))['total'] ?? 0) . "
                                        </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>

                                    <!-- SLA Information -->
                                    <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                        <h4 style='color: #856404;'>⏰ SLA Reminder</h4>
                                        <p style='color: #856404;'>
                                            <strong>Priority: " . ucfirst($priority) . "</strong><br>
                                            " . ($priority == 'high' ? 
                                                'Response required within 1 hour' : 
                                                ($priority == 'medium' ? 
                                                 'Response required within 4 hours' : 
                                                 'Response required within 24 hours')) . "<br>
                                            Current time: " . date('g:i A') . "
                                        </p>
                                    </div>

                                    <!-- Support Section -->
                                    <div class='support-section'>
                                        <p class='support-text'>Ticket assigned to: Unassigned</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");

            // Success message
            ?>
            <script>
                Swal.fire({
                    title: 'Success!',
                    html: 'Support ticket created successfully! Your ticket number is: <strong class="text-success"><?php echo $ticket_number ?></strong><br><br><small>You will receive a confirmation email with ticket details.</small>',
                    icon: 'success',
                    background: '#ffffff',
                    color: '#000000',
                    iconColor: '#28a745',
                    confirmButtonColor: '#3085d6'
                });
            </script>
            <?php

            $success = "Support ticket created successfully! Your ticket number is: <strong>" . $ticket_number . "</strong>";
            // Clear form
            $_POST = array();
        } else { ?>
            <script>
                Swal.fire({
                    title: 'Connection Problem!',
                    html: 'Failed to create ticket: <strong><?php echo mysqli_error($conn) ?></strong>',
                    icon: 'error',
                    background: '#ffffff',
                    color: '#000000',
                    iconColor: '#28a745',
                    confirmButtonColor: '#3085d6'
                });
            </script>
        <?php
        }
    }
}
?>
<!-- Create ticket form similar to your HTML structure -->