<?php
header('Content-Type: application/json; charset=utf-8');
include('../connection.php');

date_default_timezone_set('Asia/Dhaka');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request method'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$problem = trim($_POST['problem'] ?? '');
$assign = trim($_POST['assign'] ?? '');
$location = trim($_POST['location'] ?? '');
$createdAt = trim($_POST['created_at'] ?? '');
$status = trim($_POST['status'] ?? '');
$endTime = trim($_POST['end_time'] ?? '');
$rechargeId = trim($_POST['recharge_id'] ?? '');
$userId = trim($_POST['user_id'] ?? '');
$name = trim($_POST['name'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$priority = trim($_POST['priority'] ?? ($_POST['priroty'] ?? ''));
$createBy = trim($_POST['create_by'] ?? '');
$checkTime = trim($_POST['check_time'] ?? '');
$remark = trim($_POST['remark'] ?? '');
$checkCount = trim($_POST['check_count'] ?? '0');

if ($problem === '' || $rechargeId === '') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Problem and recharge ID are required'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($createdAt === '') {
    $createdAt = date('d-m-Y h:i A');
}

if ($endTime === '') {
    $endTime = $createdAt;
}

if ($status === '') {
    $status = 'pending';
}

if ($priority === '') {
    $priority = 'normal';
}

$stmt = $conn->prepare('INSERT INTO ticket (problem, assign, location, created_at, status, end_time, recharge_id, user_id, name, phone, priroty, create_by, check_time, remark, check_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$stmt->bind_param(
    'sssssssssssssss',
    $problem,
    $assign,
    $location,
    $createdAt,
    $status,
    $endTime,
    $rechargeId,
    $userId,
    $name,
    $phone,
    $priority,
    $createBy,
    $checkTime,
    $remark,
    $checkCount
);

if ($stmt->execute()) {
    echo json_encode([
        'status' => 'success',
        'message' => 'Ticket created successfully',
        'ticket_id' => $conn->insert_id
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode([
    'status' => 'error',
    'message' => 'Failed to create ticket'
], JSON_UNESCAPED_UNICODE);
