<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Handle ticket submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $priority = $_POST['priority'];
    $subject = $_POST['subject']; 
    $description = $_POST['description'];
    $category = $_POST['category'];
    $attachments = $_FILES['attachments'];

    $sql = "INSERT INTO support_tickets (user_id, subject, description, category, priority, status, created_at) 
            VALUES (?, ?, ?, ?, ?, 'OPEN', NOW())";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('issss', $_SESSION['user_id'], $subject, $description, $category, $priority);

    if ($stmt->execute()) {
        $ticket_id = $conn->insert_id;

        // Handle file uploads if any
        if (!empty($_FILES['attachments']['name'][0])) {
            $upload_dir = 'uploads/tickets/';
            foreach ($_FILES['attachments']['tmp_name'] as $key => $tmp_name) {
                $file_name = $ticket_id . '_' . basename($_FILES['attachments']['name'][$key]);
                $file_path = $upload_dir . $file_name;
                
                if (move_uploaded_file($tmp_name, $file_path)) {
                    $sql = "INSERT INTO ticket_attachments (ticket_id, file_name, file_path) VALUES (?, ?, ?)";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param('iss', $ticket_id, $_FILES['attachments']['name'][$key], $file_path);
                    $stmt->execute();
                }
            }
        }
        
        $_SESSION['success'] = 'Support ticket created successfully! Ticket #' . $ticket_id;
        header('Location: view_ticket.php?id=' . $ticket_id);
        exit();
    } else {
        $_SESSION['error'] = 'Failed to create ticket. Please try again.';
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Submit Support Ticket')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Support', 'title' => 'Submit Ticket')); ?>

                    <div class="row justify-content-center">
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Create Support Ticket</h4>
                                </div>
                                <div class="card-body">
                                    <?php if (isset($_SESSION['error'])): ?>
                                        <div class="alert alert-danger">
                                            <?php 
                                            echo $_SESSION['error']; 
                                            unset($_SESSION['error']);
                                            ?>
                                        </div>
                                    <?php endif; ?>

                                    <form action="submit_ticket.php" method="POST" enctype="multipart/form-data" class="needs-validation" novalidate>
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Category</label>
                                                <select name="category" class="form-select" required>
                                                    <option value="">Select Category</option>
                                                    <option value="technical">Technical Issue</option>
                                                    <option value="billing">Billing Query</option>
                                                    <option value="feature">Feature Request</option>
                                                    <option value="other">Other</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Priority</label>
                                                <select name="priority" class="form-select" required>
                                                    <option value="">Select Priority</option>
                                                    <option value="low">Low</option>
                                                    <option value="medium">Medium</option>
                                                    <option value="high">High</option>
                                                    <option value="urgent">Urgent</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Subject</label>
                                            <input type="text" class="form-control" name="subject" required>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Description</label>
                                            <textarea class="form-control" name="description" rows="6" required></textarea>
                                            <small class="text-muted">Please provide detailed information about your issue</small>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Attachments</label>
                                            <input type="file" class="form-control" name="attachments[]" multiple>
                                            <small class="text-muted">You can upload multiple files (max 5MB each)</small>
                                        </div>

                                        <div class="text-end">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-send-plane-line align-bottom me-1"></i> Submit Ticket
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
    // Form validation
    (function() {
        'use strict'
        var forms = document.querySelectorAll('.needs-validation')
        Array.prototype.slice.call(forms).forEach(function(form) {
            form.addEventListener('submit', function(event) {
                if (!form.checkValidity()) {
                    event.preventDefault()
                    event.stopPropagation() 
                }
                form.classList.add('was-validated')
            }, false)
        })
    })()

    // File size validation
    document.querySelector('input[type="file"]').addEventListener('change', function() {
        const maxSize = 5 * 1024 * 1024; // 5MB
        let files = this.files;
        
        for (let i = 0; i < files.length; i++) {
            if (files[i].size > maxSize) {
                alert('File ' + files[i].name + ' exceeds 5MB size limit');
                this.value = '';
                return;
            }
        }
    });
    </script>
</body>
</html>