<?php
require_once 'config.php';

$conn = getConnection();

$id          = $_POST['id']          ?? '';
$problem     = $_POST['problem']     ?? '';
$assign      = $_POST['assign']      ?? '';
$end_time    = $_POST['end_time']    ?? '';
$status      = $_POST['status']      ?? '';
$recharge_id = $_POST['recharge_id'] ?? '';
$name        = $_POST['name']        ?? '';
$phone       = $_POST['phone']       ?? '';
$user_id     = $_POST['user_id']     ?? '';
$priority    = $_POST['priority']    ?? '';
$create_by   = $_POST['create_by']   ?? '';
$location    = $_POST['location']    ?? '';
$check_time  = $_POST['check_time']  ?? '';
$remark      = $_POST['remark']      ?? '';
$isAdmin     = $_POST['isAdmin']     ?? '';
$assign_at   = $_POST['assign_at']   ?? '';
$closed_by   = $_POST['closed_by']   ?? '';
$closed_at   = $_POST['closed_at']   ?? '';

if (empty($id)) {
    echo json_encode(["message" => "Ticket ID is required"]);
    exit;
}

$check_count_sql = ($isAdmin === '1') ? ", check_count = check_count + 1" : "";

$sql = "UPDATE ticket SET problem=?, assign=?, end_time=?, status=?, recharge_id=?,
        name=?, phone=?, user_id=?, priroty=?, create_by=?, location=?,
        check_time=?, remark=?, assign_at=?, closed_by=?, closed_at=?
        $check_count_sql WHERE id=?";

$stmt = $conn->prepare($sql);
$stmt->bind_param(
    "ssssssssssssssssi",
    $problem,
    $assign,
    $end_time,
    $status,
    $recharge_id,
    $name,
    $phone,
    $user_id,
    $priority,
    $create_by,
    $location,
    $check_time,
    $remark,
    $assign_at,
    $closed_by,
    $closed_at,
    $id
);

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

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