<?php
session_start();
include "../../connect/db.php";
csrf_verify();

$user = $_SESSION['chap'];  // Assuming 'chap' is the session variable for the user

function generateTicketId() {
    $prefix = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), 0, 7);
    $randomNumber = mt_rand(1000, 9999);
    $datePart = date('m-Y');
    return "{$prefix}/{$randomNumber}/{$datePart}";
}

if (isset($_POST['department']) && isset($_POST['message'])) {
    $department = mysqli_real_escape_string($mysqli, $_POST['department']);
    $message = mysqli_real_escape_string($mysqli, $_POST['message']);
    

  // Generate a unique ticket ID
  $ticket_id = generateTicketId();


  $sql = mysqli_query($mysqli,"SELECT * FROM users WHERE email = '$user' ");

  $row = mysqli_fetch_assoc($sql);

 $name  = $row['firstname']." ".$row['middlename']." ".$row['lastname'];

 // Prepare and execute the INSERT query
 $query = "INSERT INTO support_tickets (user, department, message, name, ticket_id, created_at) VALUES (?, ?, ?, ?, ?, NOW())";
 $stmt = $mysqli->prepare($query);
 $stmt->bind_param('sssss', $user, $department, $message, $name, $ticket_id);


    if ($stmt->execute()) {
        echo "success";
    } else {
        echo "error";
    }

    $stmt->close();
}

$mysqli->close();
?>
