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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $conn->real_escape_string($_POST['name']);
    $email = $conn->real_escape_string($_POST['email']);
    $subject = $conn->real_escape_string($_POST['subject']);
    $message = $conn->real_escape_string($_POST['message']);
    $rating = isset($_POST['rating']) ? intval($_POST['rating']) : 0;
    $type = $conn->real_escape_string($_POST['type']);
    $loan_reference = isset($_POST['loan_reference']) ? $conn->real_escape_string($_POST['loan_reference']) : '';
    
    // Get user details for notification
    $userQuery = mysqli_query($conn, "SELECT first_name, last_name, email as user_email FROM users WHERE id='$user_id'");
    $userData = mysqli_fetch_assoc($userQuery);
    $first_name = $userData['first_name'];
    $last_name = $userData['last_name'];
    $user_email = $userData['user_email'];
    
    // If name is empty, use user's name
    if (empty($name)) {
        $name = $first_name . ' ' . $last_name;
    }
    
    // If email is empty, use user's email
    if (empty($email)) {
        $email = $user_email;
    }
    
    // Validate required fields
    if (empty($subject) || empty($message) || empty($type)) { ?>
        <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
    } elseif ($rating == 0 && $type != 'suggestion') {  ?>
        <script>
            Swal.fire({
                title: 'All Fields Required',
                text: 'Please provide a rating for your feedback.',
                icon: 'error',
                background: '#ffffff',
                color: '#000000',
                iconColor: '#28a745',
                confirmButtonColor: '#3085d6'
            });
        </script>
    <?php
    } else {
        $sql = "INSERT INTO feedback (user_id, name, email, subject, message, rating, type, loan_reference) 
                VALUES ('$user_id', '$name', '$email', '$subject', '$message', '$rating', '$type', '$loan_reference')";
        
        if (mysqli_query($conn, $sql)) {
            $feedback_id = mysqli_insert_id($conn);
            
            // Generate rating stars
            $rating_stars = '';
            for ($i = 1; $i <= 5; $i++) {
                if ($i <= $rating) {
                    $rating_stars .= '★';
                } else {
                    $rating_stars .= '☆';
                }
            }
            
            // Get user's active bots for context
            $activeBotsQuery = mysqli_query($conn, "SELECT COUNT(*) as active_bots FROM user_bot_subscriptions WHERE user_id='$user_id' AND status='active'");
            $activeBotsData = mysqli_fetch_assoc($activeBotsQuery);
            $active_bots = $activeBotsData['active_bots'] ?? 0;
            
            // Get IP address
            $user_ip = $_SERVER['REMOTE_ADDR'];
            
            // 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 submitting your feedback!</strong><br>
                                    We truly value your input and will use it to improve your experience.
                                </p>

                                <!-- Feedback Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>Feedback ID:</strong> FB-" . $feedback_id . "<br>
                                        <strong>Type:</strong> " . ucfirst($type) . "<br>
                                        " . ($rating > 0 ? "<strong>Rating:</strong> <span style='color: #ffc107; font-size: 18px;'>" . $rating_stars . "</span> (" . $rating . "/5)<br>" : "") . "
                                        <strong>Subject:</strong> " . htmlspecialchars($subject) . "<br>
                                        <strong>Submitted Date:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>From IP:</strong> " . $user_ip . "<br>
                                        <strong>Reference:</strong> " . (!empty($loan_reference) ? htmlspecialchars($loan_reference) : 'N/A') . "
                                    </div>
                                </div>

                                <!-- Your Message -->
                                <div class='message-section'>
                                    <h3 style='color: #2c3e50;'>Your Feedback 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($message)) . "</p>
                                    </div>
                                </div>

                                <!-- What Happens Next -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>What Happens Next?</h3>
                                    <p style='color: #6c757d;'>Here's how we handle your feedback:</p>
                                    <ul style='color: #6c757d;'>
                                        <li><strong>Review:</strong> Our team will review your feedback within 24 hours</li>
                                        <li><strong>Analysis:</strong> We'll analyze it along with other user feedback</li>
                                        <li><strong>Action:</strong> If needed, we'll implement improvements</li>
                                        <li><strong>Follow-up:</strong> We may contact you for clarification if needed</li>
                                    </ul>
                                </div>

                                <!-- Feedback Impact -->
                                <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #0056b3;'>🌟 Your Feedback Makes a Difference</h4>
                                    <p style='color: #0056b3;'>
                                        Based on user feedback like yours, we've recently:<br>
                                        • Improved our trading bot algorithms<br>
                                        • Enhanced the user dashboard interface<br>
                                        • Added new security features<br>
                                        • Reduced withdrawal processing times
                                    </p>
                                </div>

                                <!-- Action Buttons -->
                                <div style='text-align: center; margin: 30px 0;'>
                                    <a href='" . $myUrl . "/contact.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;'>
                                        Contact Support
                                    </a>
                                    <a href='" . $myUrl . "/dashboard.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 Dashboard
                                    </a>
                                </div>

                                <!-- Appreciation Section -->
                                <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0; text-align: center;'>
                                    <h4 style='color: #155724;'>🙏 Thank You!</h4>
                                    <p style='color: #155724;'>
                                        Your feedback helps us create a better trading experience for everyone.<br>
                                        We appreciate you being part of the " . $sitename . " community!
                                    </p>
                                </div>

                                <!-- Support Section -->
                                <div class='support-section'>
                                    <p class='support-text'>Have more to share? We're always listening!</p>
                                    <a href='" . $myUrl . "/feedback.php' class='support-link'>Submit More Feedback</a>
                                </div>
                            </div>";

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

            // NOTIFICATION: New Feedback Received (ADMIN)
            $admin_mail_subject = "New " . ucfirst($type) . " Feedback Received - Rating: " . $rating . "/5";
            $admin_mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>New " . ucfirst($type) . " Feedback Received</h2>
                                    
                                    <p class='message'>
                                        A user has submitted new feedback that requires attention.
                                    </p>

                                    <!-- Feedback Details -->
                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Feedback ID:</strong> FB-" . $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> " . ucfirst($type) . "<br>
                                            " . ($rating > 0 ? "<strong>Rating:</strong> <span style='color: #ffc107; font-size: 16px;'>" . $rating_stars . "</span> (" . $rating . "/5)<br>" : "") . "
                                            <strong>Subject:</strong> " . htmlspecialchars($subject) . "<br>
                                            <strong>Submitted Date:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>User IP:</strong> " . $user_ip . "<br>
                                            <strong>Reference:</strong> " . (!empty($loan_reference) ? htmlspecialchars($loan_reference) : 'N/A') . "<br>
                                            <strong>User's Active Bots:</strong> " . $active_bots . "
                                        </div>
                                    </div>

                                    <!-- User's Message -->
                                    <div class='message-section'>
                                        <h3 style='color: #2c3e50;'>Feedback 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($message)) . "</p>
                                        </div>
                                    </div>

                                    <!-- User Context -->
                                    <div class='next-steps'>
                                        <h3 style='color: #2c3e50;'>User Context</h3>
                                        <p style='color: #6c757d;'>
                                            <strong>Account Age:</strong> " . (isset($userData['created_at']) ? 
                                                round((time() - strtotime($userData['created_at'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "<br>
                                            <strong>Total Feedback:</strong> " . 
                                                (mysqli_fetch_assoc(mysqli_query($conn, 
                                                    "SELECT COUNT(*) as count FROM feedback WHERE user_id='$user_id'"))['count'] ?? 0) . "<br>
                                            <strong>Average Rating:</strong> " . 
                                                (mysqli_fetch_assoc(mysqli_query($conn, 
                                                    "SELECT AVG(rating) as avg_rating FROM feedback WHERE user_id='$user_id' AND rating > 0"))['avg_rating'] ?? 'N/A') . "/5<br>
                                            <strong>Recent Activity:</strong> " . 
                                                (mysqli_fetch_assoc(mysqli_query($conn, 
                                                    "SELECT COUNT(*) as activity FROM user_activity 
                                                     WHERE user_id='$user_id' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"))['activity'] ?? 0) . " actions (7 days)
                                        </p>
                                    </div>

                                    <!-- Priority Assessment -->
                                    <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 ? '⚠️ High Priority' : 
                                             ($rating == 3 ? '📋 Medium Priority' : '✅ Normal Priority')) . 
                                            "</h4>
                                        <p style='color: " . 
                                            ($rating <= 2 ? '#721c24' : 
                                             ($rating == 3 ? '#856404' : '#155724')) . 
                                            ";'>
                                            <strong>Response Priority:</strong> " . 
                                            ($rating <= 2 ? 'HIGH - Needs urgent attention' : 
                                             ($rating == 3 ? 'MEDIUM - Review within 24 hours' : 'NORMAL - Review when possible')) . "<br>
                                            <strong>Feedback Type:</strong> " . ($type == 'complaint' ? 'Complaint - May require follow-up' : 
                                                                                ($type == 'suggestion' ? 'Suggestion - Consider for improvements' : 
                                                                                 'General 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;'>
                                            View Feedback Details
                                        </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>
                                        <a href='" . $myUrl . "/admin/feedback/reply.php?id=" . $feedback_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6f42c1; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                            Reply to User
                                        </a>
                                    </div>

                                    <!-- Notes -->
                                    <div class='support-section'>
                                        <p class='support-text'>" . 
                                            ($rating <= 2 ? '⚠️ Low rating detected. Consider reaching out to this user.' : 
                                             ($rating >= 4 ? '✅ High rating. Consider thanking the user.' : '📋 Standard feedback for review.')) . 
                                            "</p>
                                        <p class='support-text'>Response recommended within: " . 
                                            ($rating <= 2 ? '4 hours' : 
                                             ($rating == 3 ? '24 hours' : '48 hours')) . 
                                            "</p>
                                    </div>
                                </div>";

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

            // Success message
            ?>
            <script>
                Swal.fire({
                    title: 'SUCCESS',
                    html: 'Thank you for your feedback! We appreciate you taking the time to share your thoughts with us.<br><br><small>You will receive a confirmation email with your feedback details.</small>',
                    icon: 'success',
                    background: '#ffffff',
                    color: '#000000',
                    iconColor: '#28a745',
                    confirmButtonColor: '#3085d6'
                });
            </script>
            <?php
        } else { ?>
            <script>
                Swal.fire({
                    title: 'Submission Error',
                    html: 'Failed to submit feedback: <?php echo mysqli_error($conn); ?>',
                    icon: 'error',
                    background: '#ffffff',
                    color: '#000000',
                    iconColor: '#28a745',
                    confirmButtonColor: '#3085d6'
                });
            </script>
        <?php
        }
    }
}
?>