<?php
session_start();
require_once 'db.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$errors = [];
$success = '';

if (isset($_SESSION['success_message'])) {
    $success = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die('Invalid request');
    }

    $db = new Database();
    $conn = $db->connect();

    $subject = trim(filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_STRING));
    $description = trim(filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING));
    $priority = trim(filter_input(INPUT_POST, 'priority', FILTER_SANITIZE_STRING));

    if (empty($subject)) {
        $errors[] = "Subject is required";
    }
    if (empty($description)) {
        $errors[] = "Description is required";
    }
    if (empty($priority)) {
        $errors[] = "Priority is required";
    }

    $allowed_priorities = ['low', 'medium', 'high'];
    if (!in_array($priority, $allowed_priorities)) {
        $priority = 'medium';
    }

    if (empty($errors)) {
        try {
            $conn->beginTransaction();

            $stmt = $conn->prepare("
                INSERT INTO support_tickets (user_id, subject, description, priority, status, created_at)
                VALUES (?, ?, ?, ?, 'open', NOW())
            ");
            
            if (!$stmt->execute([$_SESSION['user_id'], $subject, $description, $priority])) {
                throw new Exception("Failed to create ticket");
            }
            
            $ticket_id = $conn->lastInsertId();

            $stmt = $conn->prepare("
                INSERT INTO ticket_notifications (ticket_id, user_id, message, created_at)
                VALUES (?, ?, ?, NOW())
            ");
            
            $message = "Your ticket #{$ticket_id} has been created and is being reviewed by our support team.";
            if (!$stmt->execute([$ticket_id, $_SESSION['user_id'], $message])) {
                throw new Exception("Failed to create notification");
            }

            $conn->commit();
            $_SESSION['success_message'] = "Ticket #{$ticket_id} has been successfully created!";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;

        } catch (Exception $e) {
            $conn->rollBack();
            $errors[] = "An error occurred while creating the ticket. Please try again.";
            error_log("Ticket creation error: " . $e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Support Ticket - Imators</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #000000, #0a0a0a, #141414);
            background-attachment: fixed;
        }
        .glass-effect {
            backdrop-filter: blur(16px);
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        .gradient-border {
            position: relative;
            background: linear-gradient(145deg, rgba(26, 26, 26, 0.8), rgba(45, 45, 45, 0.4));
            padding: 1px;
        }
        .gradient-border::before {
            content: '';
            position: absolute;
            inset: -1px;
            padding: 1px;
            background: linear-gradient(145deg, rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0.03));
            -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
            mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
            -webkit-mask-composite: xor;
            mask-composite: exclude;
        }
        .success-animation {
            animation: fadeInUp 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        }
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body class="bg-black min-h-screen text-white py-8">
    <div class="max-w-4xl mx-auto px-4">
        <div class="flex justify-between items-center mb-8">
            <a href="dashboard.php" class="flex items-center space-x-2">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                </svg>
                <span>Back to Dashboard</span>
            </a>
            <img src="https://cdn.imators.com/logo.png" alt="Imators Logo" class="h-8">
        </div>

        <?php if ($success): ?>
        <div class="bg-green-500/10 border border-green-500/20 text-green-400 p-4 rounded-lg mb-8 success-animation">
            <div class="flex items-center">
                <svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                </svg>
                <?php echo htmlspecialchars($success); ?>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!empty($errors)): ?>
        <div class="bg-red-500/10 border border-red-500/20 text-red-400 p-4 rounded-lg mb-8 success-animation">
            <?php foreach ($errors as $error): ?>
            <div class="flex items-center mb-2 last:mb-0">
                <svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <?php echo htmlspecialchars($error); ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <div class="gradient-border rounded-xl overflow-hidden">
            <div class="glass-effect p-6 sm:p-8">
                <div class="flex items-center mb-6">
                    <svg class="w-6 h-6 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />
                    </svg>
                    <h1 class="text-2xl font-semibold">Create Support Ticket</h1>                          
                </div>
                 <p class="text-sm font-light text-left">Creating a ticket allows our customers to get help with a product. Our systems prevent you from abusing the system, but be aware that behind you, humans are reading, so please be respectful ;)</p>         

                <form action="" method="POST" class="space-y-6" id="ticketForm">
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Subject</label>
                        <input type="text" name="subject" required value="<?php echo htmlspecialchars($subject ?? ''); ?>"
                               class="w-full px-4 py-3 rounded-lg bg-black/50 border border-white/10 focus:border-white/30 focus:outline-none"
                               placeholder="Brief description of your issue">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Priority</label>
                        <select name="priority" required
                                class="w-full px-4 py-3 rounded-lg bg-black/50 border border-white/10 focus:border-white/30 focus:outline-none">
                            <option value="low" <?php echo ($priority ?? '') === 'low' ? 'selected' : ''; ?>>Low</option>
                            <option value="medium" <?php echo ($priority ?? 'medium') === 'medium' ? 'selected' : ''; ?>>Medium</option>
                            <option value="high" <?php echo ($priority ?? '') === 'high' ? 'selected' : ''; ?>>High</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Description</label>
                        <textarea name="description" required rows="6"
                                  class="w-full px-4 py-3 rounded-lg bg-black/50 border border-white/10 focus:border-white/30 focus:outline-none resize-none"
                                  placeholder="Please provide detailed information about your issue..."><?php echo htmlspecialchars($description ?? ''); ?></textarea>
                    </div>

                    <div class="flex justify-end gap-4">
                        <a href="dashboard.php" 
                           class="px-6 py-2 rounded-lg border border-white/10 hover:bg-white/5 transition-colors text-gray-300">
                            Cancel
                        </a>
                        <button type="submit"
                                class="px-6 py-2 bg-white text-black rounded-lg font-medium hover:bg-gray-100 transition-all">
                            Create Ticket
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
    document.getElementById('ticketForm').addEventListener('submit', function(e) {
        if (this.submitted) {
            e.preventDefault();
            return;
        }
        
        const submitButton = this.querySelector('button[type="submit"]');
        submitButton.disabled = true;
        submitButton.innerHTML = `
            <svg class="animate-spin -ml-1 mr-3 h-5 w-5 inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            Creating ticket...
        `;
        
        this.submitted = true;
    });

    const messages = document.querySelectorAll('.success-animation');
    if (messages.length) {
        setTimeout(() => {
            messages.forEach(msg => {
                msg.style.opacity = '0';
                setTimeout(() => msg.remove(), 300);
            });
        }, 5000);
    }
    </script>
</body>
</html>