<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

function safe_base64_decode($base64Text) {
    $base64Text = preg_replace('/\s+/', '', $base64Text);
    if (!preg_match('/^[A-Za-z0-9+\/=]*$/', $base64Text)) {
        throw new Exception("Invalid Base64 string");
    }
    $decoded = base64_decode($base64Text, true); 
    if ($decoded === false) {
        throw new Exception("Base64 decode failed");
    }
    return $decoded;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $post_data = file_get_contents('php://input');
    $json_data = json_decode($post_data, true);
    $decode_Data = isset($json_data['data']) ? $json_data['data'] : 'null';
    $json_data_first = safe_base64_decode($decode_Data);
    $json_data_decode = json_decode($json_data_first, true);

	$mac_address_get = isset($json_data_decode['mac_address']) ? $json_data_decode['mac_address'] : 'null';
	$parent_control_get = isset($json_data_decode['parent_control']) ? $json_data_decode['parent_control'] : 'null';

    
    
    porgress($mac_address_get , $parent_control_get);
}

function porgress($mac_address_get , $Parantpin){
    $db = new SQLite3('./.db.db');

    if (empty($mac_address_get) || empty($Parantpin)) {
        errorecho();
        return;
    }

    if (existsMAC($db, $mac_address_get)) {
        update($db , $mac_address_get , $Parantpin);
    } else {
        insertPerant($db , $mac_address_get , $Parantpin);
    }
}

function existsMAC($db, $macaddress) {
    $stmt = $db->prepare("SELECT COUNT(*) as cnt FROM pintb WHERE macad = :macad");
    $stmt->bindValue(':macad', $macaddress, SQLITE3_TEXT);
    $result = $stmt->execute();
    $row = $result->fetchArray(SQLITE3_ASSOC);

    return ($row['cnt'] > 0); // true if available, false if not
}



function update ($updatedb , $macaddress , $parantpin){
	$stmt = $updatedb->prepare("UPDATE pintb SET pin = :pin WHERE macad = :macad");
    $stmt->bindValue(':macad', $macaddress, SQLITE3_TEXT);
    $stmt->bindValue(':pin', $parantpin, SQLITE3_TEXT);
    $result = $stmt->execute();
    
    if ($result) {
        sucsessecho();
    } else {
        errorecho ();
    }
	
}

function insertPerant($db, $mac, $pin) {
    $stmt = $db->prepare("INSERT INTO pintb (macad, pin) VALUES (:macad, :pin)");
    $stmt->bindValue(':macad', $mac, SQLITE3_TEXT);
    $stmt->bindValue(':pin', $pin, SQLITE3_TEXT);

    $result = $stmt->execute();

    if ($result) {
        sucsessecho();
    } else {
        errorecho ();
    }
}


function errorecho (){
    $response = ["status" => false, "message" => "A pin not updated!"];
    header('Content-type: application/json; charset=UTF-8');
    echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

function sucsessecho(){
    
    $message =[
    'status' => true,
    'message' => 'A pin updated!'];
    
    header('Content-type: application/json; charset=UTF-8');
    echo json_encode($message, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

?>