<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once __DIR__ . "/config.php";

$data = json_decode(file_get_contents("php://input"), true);

$email    = $data['email'] ?? null;
$subject  = $data['subject'] ?? null;
$type     = $data['type'] ?? null;
$priority = $data['priority'] ?? null;
$message  = $data['message'] ?? null;

if (!$email || !$subject || !$type || !$priority || !$message) {
    echo json_encode(["status"=>"error","message"=>"All fields are required"]);
    exit;
}

// Auto-generate ticket number
$ticketno = "TKT-" . time() . rand(100,999);

$stmt = $conn->prepare("INSERT INTO tickets (email, ticketno, subject, type, priority, message, status) VALUES (?, ?, ?, ?, ?, ?, 0)");
$stmt->bind_param("ssssss", $email, $ticketno, $subject, $type, $priority, $message);

if ($stmt->execute()) {
    echo json_encode(["status"=>"success","message"=>"Ticket created successfully","ticketno"=>$ticketno]);
} else {
    echo json_encode(["status"=>"error","message"=>"Failed to create ticket"]);
}

$stmt->close();
$conn->close();
?>
