<?php 
// Include session handling
include 'services/session.php'; 

// Check if user is logged in
if (!$_SESSION['user'] || !isset($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

// Include database connection
require_once 'layouts/dbconn.php';

// Handle form submission
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subject = trim($_POST['subject'] ?? '');
    $category = $_POST['category'] ?? 'GENERAL';
    $priority = $_POST['priority'] ?? 'MEDIUM';
    $license_id = !empty($_POST['license_id']) ? (int)$_POST['license_id'] : null;
    $product_id = !empty($_POST['product_id']) ? (int)$_POST['product_id'] : null;
    $message = trim($_POST['message'] ?? '');
    
    // Validate required fields
    if (empty($subject)) {
        $error_message = 'Subject is required.';
    } elseif (empty($message)) {
        $error_message = 'Message description is required.';
    } elseif (strlen($message) < 20) {
        $error_message = 'Message must be at least 20 characters long.';
    } else {
        try {
            // Generate ticket number
            $ticket_number = 'TKT-' . date('Y') . '-' . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
            
            // Insert support ticket
            $stmt = $conn->prepare("
                INSERT INTO support_tickets 
                (ticket_number, user_id, subject, category, priority, status, license_id, product_id, created_at) 
                VALUES (?, ?, ?, ?, ?, 'OPEN', ?, ?, NOW())
            ");
            $stmt->bind_param("sisssii", $ticket_number, $user_id, $subject, $category, $priority, $license_id, $product_id);
            $stmt->execute();
            
            $ticket_id = $conn->insert_id;
            
            // Insert initial message
            $stmt = $conn->prepare("
                INSERT INTO ticket_messages 
                (ticket_id, user_id, message_type, message, created_at) 
                VALUES (?, ?, 'CUSTOMER', ?, NOW())
            ");
            $stmt->bind_param("iis", $ticket_id, $user_id, $message);
            $stmt->execute();
            
            $success_message = "Support ticket #{$ticket_number} created successfully! We'll respond within 24 hours.";
            
            // Clear form data
            $_POST = [];
            
        } catch (Exception $e) {
            $error_message = 'Error creating support ticket. Please try again.';
            error_log("Ticket creation error: " . $e->getMessage());
        }
    }
}

// Get user's licenses for dropdown
function safeQuery($conn, $query, $params = []) {
    try {
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        if (!empty($params)) {
            $types = str_repeat('s', count($params));
            $stmt->bind_param($types, ...$params);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        return $data;
    } catch (Exception $e) {
        error_log("Query error: " . $e->getMessage());
        return [];
    }
}

$user_licenses = safeQuery($conn, "
    SELECT l.license_id, l.license_key, p.name as product_name
    FROM licenses l
    JOIN products p ON l.product_id = p.product_id
    WHERE l.user_id = ? AND l.status = 'ACTIVE'
    ORDER BY p.name
", [$user_id]);

$products = safeQuery($conn, "
    SELECT p.product_id, p.name
    FROM products p
    WHERE p.is_active = 1
    ORDER BY p.name
");
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php $title = "Create Support Ticket";
    include 'partials/title-meta.php'; ?>
    
    <?php include 'partials/head-css.php'; ?>
    
    <style>
        .support-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .ticket-form {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }
        
        .priority-badge {
            padding: 0.5rem 1rem;
            border-radius: 25px;
            border: 2px solid transparent;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
        }
        
        .priority-low {
            background: #d4edda;
            color: #155724;
        }
        
        .priority-medium {
            background: #fff3cd;
            color: #856404;
        }
        
        .priority-high {
            background: #f8d7da;
            color: #721c24;
        }
        
        .priority-badge.selected {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
        }
        
        .category-card {
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
            margin-bottom: 1rem;
        }
        
        .category-card:hover, .category-card.selected {
            border-color: #007bff;
            background-color: rgba(0,123,255,0.05);
        }
        
        .help-sidebar {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 1.5rem;
        }
        
        .faq-item {
            border-bottom: 1px solid #e9ecef;
            padding: 1rem 0;
        }
        
        .faq-item:last-child {
            border-bottom: none;
        }
    </style>
</head>

<?php include 'partials/body.php'; ?>

<div id="wrapper">
    <?php $pagetitle = "Create Support Ticket"; include 'partials/menu.php'; ?>

    <div class="content-page">
        <div class="content">
            <div class="container-fluid">
                
                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="customer-dashboard.php">Dashboard</a></li>
                                    <li class="breadcrumb-item active">Create Support Ticket</li>
                                </ol>
                            </div>
                            <h4 class="page-title">
                                <i class="fas fa-headphones me-2"></i>
                                Create Support Ticket
                            </h4>
                        </div>
                    </div>
                </div>

                <!-- Support Header -->
                <div class="row">
                    <div class="col-12">
                        <div class="support-header">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h3 class="mb-3">
                                        <i class="fas fa-life-ring me-2"></i>
                                        Get Help & Support
                                    </h3>
                                    <p class="mb-0 opacity-75">
                                        Having trouble with your plugins? Our support team is here to help you.
                                        Describe your issue and we'll get back to you within 24 hours.
                                    </p>
                                </div>
                                <div class="col-md-4 text-md-end">
                                    <div class="text-white">
                                        <h5 class="mb-1">
                                            <i class="fas fa-clock me-2"></i>
                                            Response Time
                                        </h5>
                                        <p class="mb-0">Usually within 2-6 hours</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Success/Error Messages -->
                <?php if ($success_message): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i>
                    <?php echo $success_message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <?php if ($error_message): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    <?php echo $error_message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <div class="row">
                    <!-- Ticket Form -->
                    <div class="col-xl-8">
                        <div class="ticket-form">
                            <h5 class="mb-4">
                                <i class="fas fa-edit me-2"></i>
                                Create New Support Ticket
                            </h5>
                            
                            <form method="POST" id="ticketForm">
                                <!-- Subject -->
                                <div class="mb-4">
                                    <label for="subject" class="form-label">Subject *</label>
                                    <input type="text" class="form-control" id="subject" name="subject" 
                                           value="<?php echo htmlspecialchars($_POST['subject'] ?? ''); ?>" 
                                           placeholder="Brief description of your issue" required>
                                </div>

                                <!-- Category Selection -->
                                <div class="mb-4">
                                    <label class="form-label">Category *</label>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="category-card" data-category="TECHNICAL">
                                                <i class="fas fa-cogs fa-2x mb-2 text-primary"></i>
                                                <h6>Technical Issue</h6>
                                                <small class="text-muted">Plugin not working, errors, bugs</small>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="category-card" data-category="BILLING">
                                                <i class="fas fa-credit-card fa-2x mb-2 text-success"></i>
                                                <h6>Billing & Payment</h6>
                                                <small class="text-muted">Payment issues, invoices, refunds</small>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="category-card" data-category="LICENSE">
                                                <i class="fas fa-key fa-2x mb-2 text-warning"></i>
                                                <h6>License & Activation</h6>
                                                <small class="text-muted">License problems, activation issues</small>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="category-card" data-category="FEATURE">
                                                <i class="fas fa-lightbulb fa-2x mb-2 text-info"></i>
                                                <h6>Feature Request</h6>
                                                <small class="text-muted">New features, improvements</small>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="category-card" data-category="GENERAL">
                                                <i class="fas fa-question-circle fa-2x mb-2 text-secondary"></i>
                                                <h6>General Question</h6>
                                                <small class="text-muted">How-to questions, general help</small>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="category-card" data-category="INTEGRATION">
                                                <i class="fas fa-puzzle-piece fa-2x mb-2 text-danger"></i>
                                                <h6>Integration Help</h6>
                                                <small class="text-muted">Setup assistance, configuration</small>
                                            </div>
                                        </div>
                                    </div>
                                    <input type="hidden" name="category" id="categoryInput" value="GENERAL">
                                </div>

                                <!-- Priority -->
                                <div class="mb-4">
                                    <label class="form-label">Priority *</label>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="priority-badge priority-low" data-priority="LOW">
                                                <strong>Low Priority</strong>
                                                <small class="d-block">General questions, non-urgent</small>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="priority-badge priority-medium selected" data-priority="MEDIUM">
                                                <strong>Medium Priority</strong>
                                                <small class="d-block">Standard issues, normal timeline</small>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="priority-badge priority-high" data-priority="HIGH">
                                                <strong>High Priority</strong>
                                                <small class="d-block">Urgent issues, site down</small>
                                            </div>
                                        </div>
                                    </div>
                                    <input type="hidden" name="priority" id="priorityInput" value="MEDIUM">
                                </div>

                                <!-- Related License/Product -->
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-4">
                                            <label for="license_id" class="form-label">Related License (Optional)</label>
                                            <select class="form-select" name="license_id" id="license_id">
                                                <option value="">Select a license...</option>
                                                <?php foreach ($user_licenses as $license): ?>
                                                <option value="<?php echo $license['license_id']; ?>" 
                                                        <?php echo ($_POST['license_id'] ?? '') == $license['license_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($license['product_name']); ?> 
                                                    (<?php echo substr($license['license_key'], 0, 8); ?>...)
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-4">
                                            <label for="product_id" class="form-label">Related Product (Optional)</label>
                                            <select class="form-select" name="product_id" id="product_id">
                                                <option value="">Select a product...</option>
                                                <?php foreach ($products as $product): ?>
                                                <option value="<?php echo $product['product_id']; ?>"
                                                        <?php echo ($_POST['product_id'] ?? '') == $product['product_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($product['name']); ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <!-- Message -->
                                <div class="mb-4">
                                    <label for="message" class="form-label">Detailed Description *</label>
                                    <textarea class="form-control" id="message" name="message" rows="8" 
                                              placeholder="Please provide as much detail as possible about your issue. Include:
- What you were trying to do
- What happened instead
- Any error messages you saw
- Steps to reproduce the issue
- Your website URL (if relevant)"><?php echo htmlspecialchars($_POST['message'] ?? ''); ?></textarea>
                                    <div class="form-text">
                                        Minimum 20 characters. The more details you provide, the faster we can help you.
                                    </div>
                                </div>

                                <!-- Terms -->
                                <div class="mb-4">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="terms_agree" required>
                                        <label class="form-check-label" for="terms_agree">
                                            I confirm that the information provided is accurate and I agree to the 
                                            <a href="support-terms.php" target="_blank">Support Terms & Conditions</a>
                                        </label>
                                    </div>
                                </div>

                                <!-- Submit -->
                                <div class="d-grid gap-2 d-md-flex justify-content-md-between">
                                    <a href="customer-dashboard.php" class="btn btn-outline-secondary">
                                        <i class="fas fa-arrow-left me-1"></i>
                                        Back to Dashboard
                                    </a>
                                    <button type="submit" class="btn btn-primary" id="submitBtn">
                                        <i class="fas fa-paper-plane me-2"></i>
                                        Create Support Ticket
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Help Sidebar -->
                    <div class="col-xl-4">
                        <div class="help-sidebar">
                            <h5 class="mb-3">
                                <i class="fas fa-question-circle me-2"></i>
                                Quick Help
                            </h5>
                            
                            <div class="mb-4">
                                <h6>Before Creating a Ticket</h6>
                                <ul class="list-unstyled">
                                    <li class="mb-2">
                                        <i class="fas fa-check text-success me-2"></i>
                                        Check our <a href="documentation.php">Documentation</a>
                                    </li>
                                    <li class="mb-2">
                                        <i class="fas fa-check text-success me-2"></i>
                                        Browse <a href="faqs.php">Frequently Asked Questions</a>
                                    </li>
                                    <li class="mb-2">
                                        <i class="fas fa-check text-success me-2"></i>
                                        Try our <a href="sandbox-playground.php">Sandbox Environment</a>
                                    </li>
                                </ul>
                            </div>

                            <div class="mb-4">
                                <h6>Common Issues</h6>
                                <div class="faq-item">
                                    <strong>Plugin not activating?</strong>
                                    <p class="text-muted mb-0">
                                        Check your license key and ensure you haven't exceeded site limits.
                                    </p>
                                </div>
                                <div class="faq-item">
                                    <strong>Payment gateway errors?</strong>
                                    <p class="text-muted mb-0">
                                        Verify your API credentials and check if your provider is in test mode.
                                    </p>
                                </div>
                                <div class="faq-item">
                                    <strong>Integration assistance?</strong>
                                    <p class="text-muted mb-0">
                                        Include your website URL and specific error messages for faster resolution.
                                    </p>
                                </div>
                            </div>

                            <div class="text-center">
                                <div class="mb-3">
                                    <i class="fas fa-headphones fa-3x text-primary"></i>
                                </div>
                                <h6>Need Immediate Help?</h6>
                                <p class="text-muted mb-3">
                                    For urgent issues affecting live sites, mark your ticket as High Priority.
                                </p>
                                <a href="my-tickets.php" class="btn btn-outline-primary">
                                    <i class="fas fa-ticket-alt me-1"></i>
                                    View My Tickets
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <?php include 'partials/footer.php'; ?>
    </div>
</div>

<?php include 'partials/footer-scripts.php'; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Category selection
    const categoryCards = document.querySelectorAll('.category-card');
    const categoryInput = document.getElementById('categoryInput');
    
    categoryCards.forEach(card => {
        card.addEventListener('click', function() {
            categoryCards.forEach(c => c.classList.remove('selected'));
            this.classList.add('selected');
            categoryInput.value = this.dataset.category;
        });
    });
    
    // Priority selection
    const priorityBadges = document.querySelectorAll('.priority-badge');
    const priorityInput = document.getElementById('priorityInput');
    
    priorityBadges.forEach(badge => {
        badge.addEventListener('click', function() {
            priorityBadges.forEach(b => b.classList.remove('selected'));
            this.classList.add('selected');
            priorityInput.value = this.dataset.priority;
        });
    });
    
    // Form validation
    const form = document.getElementById('ticketForm');
    const submitBtn = document.getElementById('submitBtn');
    
    form.addEventListener('submit', function(e) {
        const message = document.getElementById('message').value.trim();
        
        if (message.length < 20) {
            e.preventDefault();
            alert('Please provide a more detailed description (at least 20 characters).');
            return false;
        }
        
        // Show loading state
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Creating Ticket...';
        submitBtn.disabled = true;
    });
    
    // Character counter for message
    const messageTextarea = document.getElementById('message');
    const charCounter = document.createElement('small');
    charCounter.className = 'text-muted float-end';
    messageTextarea.parentNode.appendChild(charCounter);
    
    messageTextarea.addEventListener('input', function() {
        const length = this.value.length;
        charCounter.textContent = `${length} characters`;
        
        if (length < 20) {
            charCounter.className = 'text-danger float-end';
        } else {
            charCounter.className = 'text-muted float-end';
        }
    });
    
    // Initialize character counter
    messageTextarea.dispatchEvent(new Event('input'));
});
</script>

</body>
</html>