<?php
// ✅ CORS 허용
$allowed_origins = [
    'https://it7.kr',
    'https://www.it7.kr'
];

if (isset($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) {
    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Headers: Content-Type, Authorization");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
}

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    http_response_code(200);
    exit();
}

function yt_history_log_download(string $sessionId, string $youtubeUrl, array $speedOption): ?int
{
    $logId = null;

    $dbHost = '192.168.0.11';
    $dbPort = 3307;
    $dbUser = 'it7';
    $dbPass = '!dkdlxltpqms3881';
    $dbName = 'it7';

    $createSql = <<<SQL
CREATE TABLE IF NOT EXISTS youtube_download_logs (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    session_id VARCHAR(64) NOT NULL,
    youtube_url TEXT NOT NULL,
    speeds_json TEXT NOT NULL,
    status ENUM('in_progress','completed','failed') NOT NULL DEFAULT 'in_progress',
    files_json TEXT DEFAULT NULL,
    client_ip VARCHAR(45) DEFAULT NULL,
    user_agent TEXT DEFAULT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    deleted_at DATETIME DEFAULT NULL,
    INDEX idx_created_at (created_at),
    INDEX idx_session_deleted (session_id, deleted_at)
) CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL;

    try {
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

        $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName, $dbPort);
        $mysqli->set_charset('utf8mb4');

        $mysqli->query($createSql);

        $status = 'in_progress';
        $filesJson = '[]';
        $speedsJson = json_encode(array_values($speedOption), JSON_UNESCAPED_UNICODE);
        $clientIp = $_SERVER['REMOTE_ADDR'] ?? '';
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

        $stmt = $mysqli->prepare(
            'INSERT INTO youtube_download_logs (session_id, youtube_url, speeds_json, status, files_json, client_ip, user_agent)
             VALUES (?, ?, ?, ?, ?, ?, ?)'
        );

        $stmt->bind_param('sssssss', $sessionId, $youtubeUrl, $speedsJson, $status, $filesJson, $clientIp, $userAgent);
        $stmt->execute();

        $logId = (int)$mysqli->insert_id;

        $stmt->close();
        $mysqli->close();
    } catch (Throwable $t) {
        error_log('youtube_download_logs insert failed: ' . $t->getMessage());
    } finally {
        mysqli_report(MYSQLI_REPORT_OFF);
    }

    return $logId;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    session_start();

    if (!isset($_SESSION["user_id"])) {
        $_SESSION["user_id"] = uniqid();
    }

    $session_id = $_SESSION["user_id"];
    $timestamp = date("YmdHis");
    $video_filename = "video_{$session_id}_{$timestamp}.mp4";

    $youtube_url = $_POST["url"] ?? null;
    $speed_option = $_POST["speeds"] ?? [];

    if (!$youtube_url || empty($speed_option)) {
        echo json_encode(["error" => "Invalid parameters", "log" => "Missing url or speeds"]);
        exit();
    }

    // ✅ Python 실행 명령어 구성
    $python_path = "/opt/it7-nvidia-venv/bin/python";
    $script_path = "/var/www/it7/html/youtubeDownloader/youtube_download.py";
    $log_dir = "/var/www/it7/html/youtubeDownloader/logs";
    if (!is_dir($log_dir)) {
        @mkdir($log_dir, 0755, true);
    }
    $log_file = $log_dir . "/worker_" . date("Ymd") . ".log";

    $logId = yt_history_log_download($session_id, $youtube_url, $speed_option);

    $cmd = escapeshellcmd($python_path) . " " .
           escapeshellarg($script_path) . " " .
           escapeshellarg($youtube_url) . " " .
           escapeshellarg(json_encode($speed_option)) . " " .
           escapeshellarg($video_filename) . " " .
           escapeshellarg($session_id) . " >> " . escapeshellarg($log_file) . " 2>&1 &";

    // ✅ 프로세스를 완전 비동기로 시작
    $descriptorspec = [
        0 => ["pipe", "r"],
        1 => ["pipe", "w"],
        2 => ["pipe", "w"]
    ];
    $process = proc_open($cmd, $descriptorspec, $pipes);
    if (is_resource($process)) {
        proc_close($process);
    }

    // ✅ 즉시 성공 응답 반환
    echo json_encode([
        "status" => "started",
        "session_id" => $session_id,
        "log_id" => $logId
    ]);
    exit();
}
?>
