<?php
// /youtivi/api/save_playlist.php

ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/error_log');
if (!headers_sent()) {
    header('Content-Type: application/json; charset=UTF-8');
}

// Optional include (only if you rely on helpers elsewhere)
@include_once __DIR__ . '/../includes/functions.php';

// ---- Input ----
$mac   = isset($_GET['mac'])   ? trim($_GET['mac'])   : '';
$uuid  = isset($_GET['uuid'])  ? trim($_GET['uuid'])  : '';
$name  = isset($_GET['name'])  ? trim($_GET['name'])  : '';
$uname = isset($_GET['uname']) ? trim($_GET['uname']) : '';
$pword = isset($_GET['pword']) ? trim($_GET['pword']) : '';

// Minimal validation (match old behavior: do not over-reject)
if ($mac === '' || $uname === '' || $pword === '') {
    echo json_encode([
        'status'  => 'error',
        'message' => 'There was a problem. Please try again later.'
    ]);
    exit;
}

// ---- Helpers ----
function genPlaylistId(): string {
    $time = microtime(true) . ':' . bin2hex(random_bytes(8));
    return hash('sha256', $time);
}
function now(): string {
    $tz = @date_default_timezone_get();
    if (!$tz) { $tz = 'UTC'; }
    date_default_timezone_set($tz);
    return date('Y-m-d H:i:s');
}
function randomPlaylistName(): string {
    static $names = [
        "📺 UltraStream","🎬 CineMax","📡 NetWave","🔥 FireStream","🌐 GlobeTV","🎥 MovieZone",
        "🌟 StarView","📻 RadioCast","💎 DiamondTV","🌊 OceanStream","🚀 RocketTV","🎶 MusicFlow",
        "🍿 PopcornTime","🛰️ SatView","🎯 TargetStream","📽️ FilmBox","💫 GalaxyCast","⚡ FlashStream",
        "🏆 PrimeTV","🖥️ StreamX","🌈 RainbowTV","🎉 PartyStream","🦅 EagleCast","🏝️ IslandView",
        "🔮 VisionTV","🎤 StageCast","📦 BoxStream","🛡️ ShieldView","🌌 SpaceStream","💥 BoomCast",
        "🎧 AudioWave","🎭 DramaBox","🌻 SunStream","📊 InfoCast","🐬 DolphinTV","🪐 OrbitView",
        "🌴 TropicCast","📜 StoryTV","💃 DanceStream","🥇 GoldCast"
    ];
    return $names[array_rand($names)];
}

if ($name === '' || strtolower($name) === 'ran') {
    $name = randomPlaylistName();
}

// ---- DB ----
try {
    $db = new SQLite3(__DIR__ . '/.db.db');
    // Create table if missing (safe)
    $db->exec('CREATE TABLE IF NOT EXISTS ibof (
        id        INTEGER PRIMARY KEY AUTOINCREMENT,
        plid      TEXT    NOT NULL,
        name      TEXT    NOT NULL,
        macad     TEXT    NOT NULL,
        uuid      TEXT    NOT NULL,
        username  TEXT    NOT NULL,
        password  TEXT    NOT NULL,
        cdate     TEXT    NOT NULL,
        udate     TEXT    NOT NULL,
        mark      INTEGER NOT NULL DEFAULT 0,
        protec    INTEGER NOT NULL DEFAULT 0
    )');

    $pid  = genPlaylistId();
    $when = now();

    $stmt = $db->prepare('INSERT INTO ibof
        (plid, name, macad, uuid, username, password, cdate, udate, mark, protec)
        VALUES
        (:plid,:name,:mac,:uuid,:uname,:pword,:cdate,:udate,0,0)');
    $stmt->bindValue(':plid',  $pid,   SQLITE3_TEXT);
    $stmt->bindValue(':name',  $name,  SQLITE3_TEXT);
    $stmt->bindValue(':mac',   $mac,   SQLITE3_TEXT);
    $stmt->bindValue(':uuid',  $uuid,  SQLITE3_TEXT);
    $stmt->bindValue(':uname', $uname, SQLITE3_TEXT);
    $stmt->bindValue(':pword', $pword, SQLITE3_TEXT);
    $stmt->bindValue(':cdate', $when,  SQLITE3_TEXT);
    $stmt->bindValue(':udate', $when,  SQLITE3_TEXT);

    $ok = $stmt->execute();

    if ($ok === false) {
        echo json_encode([
            'status'  => 'error',
            'message' => 'There was a problem. Please try again later.'
        ]);
        exit;
    }

    // *** IMPORTANT: return the legacy shape ***
    echo json_encode([
        'status'  => 'success',
        'message' => "Successfully added the playlist ➤ $name"
    ], JSON_UNESCAPED_UNICODE);
    exit;

} catch (Throwable $e) {
    error_log('save_playlist error: ' . $e->getMessage());
    echo json_encode([
        'status'  => 'error',
        'message' => 'There was a problem. Please try again later.'
    ]);
    exit;
}
