<?php
/**
 * Oracle Instant Client Setup Script
 * Run from Command Prompt:
 *   D:\laragon\bin\php\php-8.3.30-Win32-vs16-x64\php.exe D:\laragon\app\laraveladmin\setup_oracle.php
 */

set_time_limit(0);
ini_set('default_socket_timeout', 120);

$phpDir     = 'D:\\laragon\\bin\\php\\php-8.3.30-Win32-vs16-x64';
$phpIni     = $phpDir . '\\php.ini';
$zipDest    = 'D:\\instantclient_19.zip';
$extractDir = 'D:\\';

$downloadUrls = [
    'https://download.oracle.com/otn_software/nt/instantclient/1919000/instantclient-basic-windows.x64-19.19.0.0.0dbru.zip',
    'https://download.oracle.com/otn_software/nt/instantclient/1921000/instantclient-basic-windows.x64-19.21.0.0.0dbru.zip',
    'https://download.oracle.com/otn_software/nt/instantclient/1923000/instantclient-basic-windows.x64-19.23.0.0.0dbru.zip',
];

echo "=== Oracle Instant Client Setup ===\n\n";

// ── STEP 1: Download ──────────────────────────────────────────────────────────
if (file_exists($zipDest) && filesize($zipDest) > 5_000_000) {
    echo "[SKIP] Zip already at $zipDest (" . round(filesize($zipDest)/1048576, 1) . " MB)\n";
} else {
    echo "[1/4] Downloading Oracle Instant Client 19 (~80 MB)...\n";
    $downloaded = false;

    foreach ($downloadUrls as $url) {
        echo "      Trying: $url\n";
        $ctx = stream_context_create([
            'http' => [
                'timeout'         => 180,
                'follow_location' => true,
                'method'          => 'GET',
                'header'          => "Accept: application/zip, */*\r\nUser-Agent: Mozilla/5.0\r\n",
            ],
            'ssl' => [
                'verify_peer'      => false,
                'verify_peer_name' => false,
            ],
        ]);

        $data = @file_get_contents($url, false, $ctx);

        if ($data && strlen($data) > 5_000_000) {
            file_put_contents($zipDest, $data);
            echo "      Downloaded: " . round(strlen($data)/1048576, 1) . " MB\n";
            $downloaded = true;
            break;
        }
        echo "      Failed (size: " . strlen($data ?? '') . " bytes)\n";
    }

    if (!$downloaded) {
        echo "\n[ERROR] Auto-download failed. Please manually download Oracle Instant Client 19\n";
        echo "Basic (Windows x64) from:\n";
        echo "  https://www.oracle.com/database/technologies/instant-client/winx64-64-downloads.html\n";
        echo "Save the zip as: D:\\instantclient_19.zip\n";
        echo "Then re-run this script.\n";
        exit(1);
    }
}

// ── STEP 2: Extract ───────────────────────────────────────────────────────────
echo "\n[2/4] Extracting zip...\n";
$zip = new ZipArchive();
if ($zip->open($zipDest) !== true) {
    echo "[ERROR] Cannot open zip: $zipDest\n";
    exit(1);
}
$zip->extractTo($extractDir);
$zip->close();
echo "      Extracted to $extractDir\n";

// ── STEP 3: Find extracted folder & copy DLLs ────────────────────────────────
echo "\n[3/4] Finding and copying Oracle DLLs to PHP directory...\n";
$icDir = null;
foreach (glob('D:\\instantclient_*', GLOB_ONLYDIR) as $d) {
    if (file_exists($d . '\\oci.dll')) {
        $icDir = $d;
        break;
    }
}

if (!$icDir) {
    echo "[ERROR] Could not find instantclient folder with oci.dll under D:\\\n";
    foreach (glob('D:\\instantclient_*') as $d) echo "  Found: $d\n";
    exit(1);
}

echo "      Instant Client folder: $icDir\n";

$copied = 0;
foreach (glob($icDir . '\\*.dll') as $dll) {
    $dest = $phpDir . '\\' . basename($dll);
    if (@copy($dll, $dest)) {
        echo "      + " . basename($dll) . "\n";
        $copied++;
    } else {
        echo "      FAILED: " . basename($dll) . "\n";
    }
}
echo "      Total DLLs copied: $copied\n";

// ── STEP 4: Verify php.ini ────────────────────────────────────────────────────
echo "\n[4/4] Verifying php.ini...\n";
$ini = file_get_contents($phpIni);

if (!preg_match('/^extension=oci8_19/m', $ini)) {
    $ini = preg_replace('/^;extension=oci8_19.*/m', 'extension=oci8_19  ; Use with Oracle Database 19 Instant Client', $ini);
    file_put_contents($phpIni, $ini);
    echo "      Enabled: extension=oci8_19\n";
} else {
    echo "      OK: extension=oci8_19 already enabled\n";
}

if (!preg_match('/^extension=pdo_oci/m', $ini)) {
    $ini = preg_replace('/^;extension=pdo_oci.*/m', 'extension=pdo_oci', $ini);
    file_put_contents($phpIni, $ini);
    echo "      Enabled: extension=pdo_oci\n";
} else {
    echo "      OK: extension=pdo_oci already enabled\n";
}

echo "\n=== SETUP COMPLETE ===\n";
echo "Now verify the extensions loaded:\n";
echo "  D:\\laragon\\bin\\php\\php-8.3.30-Win32-vs16-x64\\php.exe -m\n\n";
echo "You should see 'oci8' and 'PDO_OCI' in the list.\n\n";
echo "Then restart Laragon: Stop All -> Start All\n";
