<?php
require dirname( dirname(__FILE__) ).'/inc/config.php';
require dirname( dirname(__FILE__) ).'/inc/FunctionQuery.php';
require dirname( dirname(__FILE__) ).'/inc/keyvaliation.php';
$h = new FunctionQuery($service);
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);

// Helper function: Send JSON response
function respond($code, $result, $msg) {
    echo json_encode([
        "ResponseCode" => $code,
        "Result" => $result,
        "ResponseMsg" => $msg
    ]);
    exit;
}

// Helper function: Send OneSignal Notification
function sendNotification($uid, $msg, $title, $set) {
    $fields = [
        'app_id' => $set['one_key'],
        'included_segments' => ['All'],
        'filters' => [[
            'field' => 'tag',
            'key' => 'userid',
            'relation' => '=',
            'value' => $uid
        ]],
        'contents' => ["en" => $msg],
        'headings' => ["en" => $title],
        'android_channel_id' => $set['one_cust']
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic ' . $set['one_hash']
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_exec($ch);
    curl_close($ch);
}

// Helper function: Log Notification
function logNotification($uid, $title, $description) {
    
    $timestamp = date("Y-m-d H:i:s");
    $h->serviceinsertdata_Api(
        ["uid", "datetime", "description", "title"],
        [$uid, $timestamp, $description, $title],
        "tbl_notification"
    );
}

// Helper function: Save Base64 image to server
function saveBase64Image($base64_string, $folder, $prefix = 'img') {
    if (empty($base64_string)) return null;

    $matches = [];
    if (preg_match('/^data:image\/(\w+);base64,/', $base64_string, $matches)) {
        $ext = $matches[1]; // jpg, png, etc.
        $base64_string = substr($base64_string, strpos($base64_string, ',') + 1);
        $base64_string = base64_decode($base64_string);

        if ($base64_string === false) return null;

        $dir = "images/$folder/";
        if (!file_exists($dir)) mkdir($dir, 0777, true);

        $filename = $dir . $prefix . '_' . time() . '_' . rand(1000, 9999) . ".$ext";
        file_put_contents($filename, $base64_string);
        return $filename;
    }

    return null;
}

// Input fields
$status = $data['status'] ?? null;
$load_id = $data['load_id'] ?? null;
$owner_id = $data['owner_id'] ?? null;
$load_type = $data['load_type'] ?? '';
$sign = $data['sign'] ?? null;

if (!$status || !$load_id || !$owner_id) {
    respond("401", "false", "Missing required fields.");
}

if ($owner_id == 3) {
    respond("200", "false", "Demo account restriction. Please register to enable this action.");
}

// Save only one sign image based on status
$sign_path = saveBase64Image($sign, 'sign', ($status == 1 ? 'pick' : 'drop'));

// Prepare update
$table = "tbl_load";


switch ($status) {
    case 1:
        $field = [
            'load_status' => 'Load_start',
            'flow_id' => ($load_type === 'POST_LOAD') ? 2 : 7
        ];
        if ($sign_path) {
            $field['pick_sign'] = $sign_path;
        }
        $msg = "Load Pick up Successfully.";
        $title = "Check Your Load ID#$load_id Pick up Successfully!!";
        break;

    case 2:
        $field = [
            'load_status' => 'Completed',
            'flow_id' => ($load_type === 'POST_LOAD') ? 3 : 8
        ];
        if ($sign_path) {
            $field['drop_sign'] = $sign_path;
        }
        $msg = "Load Drop Successfully.";
        $title = "Check Your Load ID#$load_id Drop Successfully!!";
        break;

    default:
        respond("400", "false", "Invalid status value.");
}

// Update DB
$where = "WHERE id = " . intval($load_id) . " AND lorry_owner_id = " . intval($owner_id);
$updateResult = $h->serviceupdateData_Api($field, $table, $where);

// Send notification
$getUser = $service->query("SELECT uid FROM tbl_load WHERE id = " . intval($load_id))->fetch_assoc();
$uid = $getUser['uid'] ?? null;

if ($uid) {
    sendNotification($uid, $msg, $title, $set);
    logNotification($uid, $title, $msg);
}

respond("200", "true", $msg);
