<?php
set_time_limit(0);
ignore_user_abort(true);

// =========================
//  CONEXIÓN A MYSQL
// =========================
$mysqli = new mysqli("167.172.224.160", "root", "33comRxXMysql", "MS_GPS");

if ($mysqli->connect_errno) {
    file_put_contents("gps_server.log", "ERROR MYSQL: " . $mysqli->connect_error . "\n", FILE_APPEND);
    exit;
}

$host = "167.172.224.160";
$port = 5000;

// =========================
//  SOCKET SERVER
// =========================
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);

if(!socket_bind($sock, $host, $port)){
    file_put_contents("gps_server.log", "ERROR BIND: ".socket_strerror(socket_last_error())."\n", FILE_APPEND);
    exit;
}

socket_listen($sock);

file_put_contents("gps_server.log", "Servidor GPS escuchando en puerto $port\n", FILE_APPEND);

// =========================
// FUNCIÓN
// =========================
function convertirCoordenada($coord, $hem){
    if($coord == "" || $coord == 0) return 0;

    $grados = intval(substr($coord, 0, -7));
    $minutos = floatval(substr($coord, -7)) / 60.0;

    $decimal = $grados + $minutos;
    return ($hem == "S" || $hem == "W") ? -$decimal : $decimal;
}

// =========================
// LOOP PRINCIPAL
// =========================
while(true){

    $client = @socket_accept($sock);
    if(!$client){
        usleep(100000);
        continue;
    }

    $data = trim(@socket_read($client, 2048));
    if(!$data){
        socket_close($client);
        continue;
    }

    file_put_contents("gps_server.log", "Recibido: $data\n", FILE_APPEND);

    $dataRaw = $data;
    $data = trim($data, "*#");
    $partes = explode(",", $data);

    // Variables base
    $imei    = $partes[1] ?? "";
    $tipo    = $partes[2] ?? "";
    $hora    = $partes[3] ?? "000000";
    $valido  = $partes[4] ?? "V";
    $lat_raw = $partes[5] ?? "0";
    $lat_h   = $partes[6] ?? "N";
    $lon_raw = $partes[7] ?? "0";
    $lon_h   = $partes[8] ?? "W";
    $velocidad = floatval($partes[9] ?? 0);
    $rumbo   = intval($partes[10] ?? 0);
    $fecha   = $partes[11] ?? "010100";
    $estado  = $partes[12] ?? "";
    $mcc     = $partes[13] ?? "";
    $lac     = $partes[14] ?? "";
    $cellid  = $partes[15] ?? "";

    // Procesar coordenadas
    $lat_decimal = convertirCoordenada($lat_raw, $lat_h);
    $lon_decimal = convertirCoordenada($lon_raw, $lon_h);

    // Hora SQL
    $hora_sql = substr($hora,0,2).":".substr($hora,2,2).":".substr($hora,4,2);

    // Fecha SQL
    $fecha_sql = "20".substr($fecha,4,2)."-".substr($fecha,2,2)."-".substr($fecha,0,2);

    // Guardar en BD
    $stmt = $mysqli->prepare("
        INSERT INTO MS_GPS.GPS_Reg
        (imei, tipo, hora, fecha, latitud, longitud, velocidad, rumbo, valido,
         estado_hex, mcc, lac, cellid, raw)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->bind_param("ssssdddiisssss",
        $imei, $tipo, $hora_sql, $fecha_sql, $lat_decimal, $lon_decimal,
        $velocidad, $rumbo, $valido, $estado, $mcc, $lac, $cellid, $dataRaw
    );

    $stmt->execute();

    socket_write($client, "OK\n");
    socket_close($client);
}

socket_close($sock);
?>
