<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '../config/database.php';
include_once '../objects/ont.php';

date_default_timezone_set('Asia/Rangoon');
session_start();

// DB
$database = new Database();
$db = $database->getConnection();
$ont = new ONT($db);

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

// ✅ prevent crash
if (!$data) {
    echo json_encode(["records" => []]);
    exit;
}

// assign safely
$ont->id_no = $data->id_no ?? "";
$ont->customer_name = $data->customer_name ?? "";
$ont->city = $data->city ?? "";
$ont->status_ = $data->status_ ?? "";

// DB query
$stmt = $ont->search();
$num = $stmt->rowCount();

// result
$arr = array();
$arr["records"] = array();


// ============================
// 🔥 SMARTOLT API CALL
// ============================
$onuStatusMap = [];

if (!empty($data->olt_id) && !empty($data->smart_key)) {

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://tkknet.smartolt.com/api/onu/get_onus_administrative_statuses?olt_id=' . urlencode($data->olt_id),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => array(
            'X-Token: ' . $data->smart_key
        ),
    ));

    $response = curl_exec($curl);

    if (!curl_errno($curl)) {
        $res_data = json_decode($response);

        if (!empty($res_data->response)) {
            foreach ($res_data->response as $onu) {
                // map SN → admin_status
                $onuStatusMap[$onu->sn] = $onu->admin_status;
            }
        }
    }

    curl_close($curl);
}


// ============================
// 🔁 PROCESS DATA
// ============================

$statusMap = [
    0 => "New",
    1 => "Active",
    2 => "Inactive",
    3 => "Terminate"
];

if ($num > 0) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

        extract($row);

        // ✅ fast lookup (no more array_search)
        $status_ = $onuStatusMap[$ont_snno] ?? "";

        $sts = $statusMap[$ss] ?? "";

        $detail = array(
            "status_" => $status_,
            "id" => $id,
            "id_no" => $id_no,
            "customer_name" => $name ?? "",
            "package" => $package ?? "",
            "ont_snno" => $ont_snno ?? "",
            "port" => $port ?? "",
            "ont_id" => $ont_id ?? "",
            "mme_id" => $mme_id ?? "",
            "pppoe_name" => $pppoe_name ?? "",
            "ont_password" => $ont_password ?? "",
            "sts" => $sts,
            "status" => $ss
        );

        array_push($arr["records"], $detail);
    }
}

// output
echo json_encode($arr);
?>