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

function extract_credentials($url) {
    $parts = parse_url($url);

    if (!isset($parts['query'])) {
        return null; 
    }

    parse_str($parts['query'], $query);
    $username = isset($query['username']) ? $query['username'] : null;
    $password = isset($query['password']) ? $query['password'] : null;

    return [
        "username" => $username,
        "password" => $password
    ];
}

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';
	$playlist_id_get = isset($json_data_decode['playlist_id']) ? $json_data_decode['playlist_id'] : 'null';
    $playlist_url_get = isset($json_data_decode['playlist_url']) ? $json_data_decode['playlist_url'] : 'null';
    $playlist_name_get = isset($json_data_decode['playlist_name']) ? $json_data_decode['playlist_name'] : 'null';

    $creds = extract_credentials($playlist_url_get);
    
    $exusername =  $creds['username'];
    $expassword =  $creds['password'];
    
    
    
    porgress($playlist_name_get ,$exusername,$expassword,$playlist_id_get);
}

function porgress($PlaylitName , $Username ,$Password, $PlaylistID){
    $db = new SQLite3('./.db.db');
    
    if($PlaylitName == ''||$Username == ''||$Password == ''|| $PlaylistID == ''){
        errorecho();
    }else{
        update($db , $PlaylitName , $Username ,$Password, $PlaylistID, getCurrentDateTimeAuto());
    }
    
}

function update ($updatedb , $PlaylitName , $Username ,$Password, $PlaylistID, $Udate){
	$stmt = $updatedb->prepare("UPDATE ibof SET name = :name, username = :username, password = :password, udate = :udate WHERE plid = :plid");
    $stmt->bindValue(':name', $PlaylitName, SQLITE3_TEXT);
    $stmt->bindValue(':username', $Username, SQLITE3_TEXT);
    $stmt->bindValue(':password', $Password, SQLITE3_TEXT);
    $stmt->bindValue(':udate', $Udate, SQLITE3_TEXT);
    $stmt->bindValue(':plid', $PlaylistID, SQLITE3_TEXT);
    $stmt->execute();
    sucsessecho($updatedb, $PlaylistID);
	
}


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

function sucsessecho($dbdata, $PlaylistID){
    $ibo_query = $dbdata->query('SELECT * FROM ibof WHERE LOWER(plid)="' . $PlaylistID . '"');
    
  
    $urls;
    while ($ibo_row = $ibo_query->fetchArray(SQLITE3_ASSOC)) {
        $base_url = getuuidtodns($ibo_row['uuid'], 2);

        $urls = [
            'name'        => $ibo_row['name'],
            'id'          => $ibo_row['plid'],
            'url'         => $base_url."/get.php?username={$ibo_row['username']}&password={$ibo_row['password']}&output=ts&type=m3u_plus",
            'type'        => "URL",
            'is_protected'=> ($ibo_row['protec'] === "1") ? true : false,
            'created_at'  => $ibo_row['cdate'],
            'updated_at'  => $ibo_row['udate']
        ];
    }
    
    header('Content-type: application/json; charset=UTF-8');
    echo json_encode($urls, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

function getuuidtodns($uuid,$type){
    $db = new SQLite3('./.db.db');
    $uuid = strtolower($uuid);
    $ibo_query = $db->query('SELECT * FROM dns WHERE LOWER(uid)="' . $uuid . '"');
    $dnsname = "";
    $dnsurl = "";
    while ($ibo_row = $ibo_query->fetchArray()) {
        $dnsname = $ibo_row['title'];
        $dnsurl = $ibo_row['url'];
    }
    
    if($type == 1){
        return $dnsname;
    }else{
        return $dnsurl;
    }
    
}

function getCurrentDateTimeAuto() {
    $timezone = @date_default_timezone_get();
    if (!$timezone) {
        $timezone = 'UTC';
    }
    date_default_timezone_set($timezone);
    return date('Y-m-d H:i:s');
}

?>