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

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

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Get ticket categories
$sql_categories = "SELECT * FROM ticket_categories WHERE status = 1 ORDER BY name";
$result_categories = $conn->query($sql_categories);
$categories = [];
if ($result_categories && $result_categories->num_rows > 0) {
    while ($row = $result_categories->fetch_assoc()) {
        $categories[] = $row;
    }
}

// Generate ticket reference number
function generateTicketReference() {
    return 'TKT-' . strtoupper(substr(md5(uniqid(rand(), true)), 0, 8));
}

$ticket_ref = generateTicketReference();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Support Ticket')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/dropzone@5.9.3/dist/min/dropzone.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/dropzone@5.9.3/dist/min/dropzone.min.js"></script>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- Start right Content here -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Support', 'title' => 'Create Ticket')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <?php if (isset($_SESSION['error_message'])): ?>
                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                    <?php 
                                    echo $_SESSION['error_message']; 
                                    unset($_SESSION['error_message']);
                                    ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                </div>
                            <?php endif; ?>

                            <?php if (isset($_SESSION['success_message'])): ?>
                                <div class="alert alert-success alert-dismissible fade show" role="alert">
                                    <?php 
                                    echo $_SESSION['success_message']; 
                                    unset($_SESSION['success_message']);
                                    ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                </div>
                            <?php endif; ?>

                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Create Support Ticket</h5>
                                </div>
                                <div class="card-body">
                                    <form action="save_ticket.php" method="post" enctype="multipart/form-data">
                                        <input type="hidden" name="reference_number" value="<?php echo $ticket_ref; ?>">
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="subject" class="form-label">Subject <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" id="subject" name="subject" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="category" class="form-label">Category <span class="text-danger">*</span></label>
                                                <select class="form-select" id="category" name="category" required>
                                                    <option value="">Select Category</option>
                                                    <?php foreach ($categories as $category): ?>
                                                        <option value="<?php echo htmlspecialchars($category['name']); ?>">
                                                            <?php echo htmlspecialchars($category['name']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="priority" class="form-label">Priority</label>
                                                <select class="form-select" id="priority" name="priority">
                                                    <option value="low">Low</option>
                                                    <option value="medium" selected>Medium</option>
                                                    <option value="high">High</option>
                                                    <option value="critical">Critical</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="reference" class="form-label">Reference Number</label>
                                                <input type="text" class="form-control" id="reference" value="<?php echo $ticket_ref; ?>" readonly>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="message" class="form-label">Message <span class="text-danger">*</span></label>
                                            <textarea class="form-control" id="message" name="message" rows="6" required></textarea>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Attachments (Optional)</label>
                                            <div class="dropzone" id="fileUpload">
                                                <div class="dz-message needsclick">
                                                    <div class="mb-3">
                                                        <i class="display-4 text-muted ri-upload-cloud-2-line"></i>
                                                    </div>
                                                    <h4>Drop files here or click to upload</h4>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="text-end">
                                            <a href="index.php" class="btn btn-light me-2">Cancel</a>
                                            <button type="submit" class="btn btn-primary">Submit Ticket</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?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>
        document.addEventListener("DOMContentLoaded", function() {
            // Initialize Dropzone
            let myDropzone = new Dropzone("#fileUpload", {
                url: "save_ticket.php",
                autoProcessQueue: false,
                uploadMultiple: true,
                parallelUploads: 5,
                maxFiles: 5,
                maxFilesize: 5, // MB
                acceptedFiles: ".jpg,.jpeg,.png,.pdf,.doc,.docx,.xls,.xlsx,.txt",
                addRemoveLinks: true
            });
            
            // Handle form submission
            document.querySelector("form").addEventListener("submit", function(e) {
                e.preventDefault();
                
                // Handle files
                if (myDropzone.getQueuedFiles().length > 0) {
                    myDropzone.processQueue();
                } else {
                    // Submit form without files
                    this.submit();
                }
            });
            
            // Handle Dropzone events
            myDropzone.on("sendingmultiple", function(files, xhr, formData) {
                // Append all form data
                let form = document.querySelector("form");
                let formData = new FormData(form);
                
                for (let [key, value] of formData.entries()) {
                    xhr.append(key, value);
                }
            });
            
            myDropzone.on("successmultiple", function(files, response) {
                window.location.href = "my_tickets.php";
            });
            
            myDropzone.on("errormultiple", function(files, response) {
                console.error("Error uploading files:", response);
                alert("Error uploading files. Please try again.");
            });
        });
    </script>
</body>
</html>