<?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";

// Read input
$input = json_decode(file_get_contents('php://input'), true);
$ticket_id   = $input['ticket_id'] ?? null;
$admin_remark = $input['admin_remark'] ?? '';
$status       = $input['status'] ?? 1; // 1 = approved, 2 = rejected

if (!$ticket_id) {
    echo json_encode(["status"=>"error","message"=>"ticket_id is required"]);
    exit;
}

// Check if ticket exists
$stmt_check = $conn->prepare("SELECT * FROM tickets WHERE id=?");
$stmt_check->bind_param("i",$ticket_id);
$stmt_check->execute();
$result_check = $stmt_check->get_result();
if($result_check->num_rows == 0){
    echo json_encode(["status"=>"error","message"=>"Ticket not found"]);
    exit;
}

// Update ticket
$stmt = $conn->prepare("UPDATE tickets SET status=?, AdminRemark=? WHERE id=?");
$stmt->bind_param("isi",$status,$admin_remark,$ticket_id);

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

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