<?php
/**
 * Generates:
 *  - output/reset_all_user_passwords.sql  (UPDATE per user didar_user_id, bcrypt hash)
 *  - output/reset_all_user_passwords.csv  (email,username,display_name,new_password)
 *
 * Source: hanafivi_didash (1).sql (phpMyAdmin dump)
 */

declare(strict_types=1);

function sqlQuote(string $value): string
{
    return "'" . str_replace("'", "''", $value) . "'";
}

function normCsv(string $value): string
{
    $value = str_replace(["\r", "\n"], " ", $value);
    $value = str_replace(",", " ", $value);
    return trim($value);
}

function randPass(int $len = 14): string
{
    $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789@#%';
    $out = '';
    $max = strlen($alphabet) - 1;
    for ($i = 0; $i < $len; $i++) {
        $out .= $alphabet[random_int(0, $max)];
    }
    return $out;
}

function parseUserRowsFromDump(string $sqlText): array
{
    if (!preg_match('/INSERT INTO `users` .*? VALUES\s*(.*?);/s', $sqlText, $m)) {
        return [];
    }
    $values = $m[1];

    // Extract (...) rows safely
    $rows = [];
    $buf = '';
    $depth = 0;
    $inQuote = false;
    $prev = '';
    $len = strlen($values);
    for ($i = 0; $i < $len; $i++) {
        $ch = $values[$i];
        if ($ch === "'" && $prev !== '\\') {
            $inQuote = !$inQuote;
        }
        if (!$inQuote && $ch === '(') {
            $depth++;
        }
        if ($depth > 0) {
            $buf .= $ch;
        }
        if (!$inQuote && $ch === ')' && $depth > 0) {
            $depth--;
            if ($depth === 0) {
                $rows[] = $buf;
                $buf = '';
            }
        }
        $prev = $ch;
    }

    $users = [];
    foreach ($rows as $row) {
        $inner = substr($row, 1, -1);
        $fields = [];
        $cur = '';
        $inQ = false;
        $prev = '';
        $ilen = strlen($inner);
        for ($i = 0; $i < $ilen; $i++) {
            $ch = $inner[$i];
            if ($ch === "'" && $prev !== '\\') {
                $inQ = !$inQ;
                $cur .= $ch;
            } elseif ($ch === ',' && !$inQ) {
                $fields[] = trim($cur);
                $cur = '';
            } else {
                $cur .= $ch;
            }
            $prev = $ch;
        }
        $fields[] = trim($cur);

        // Expected columns:
        // (id, didar_user_id, email, first_name, last_name, display_name, username, password, role, is_active, api_key, last_sync, created_at)
        if (count($fields) < 13) {
            continue;
        }

        $unq = function (string $s): string {
            $s = trim($s);
            if (strtoupper($s) === 'NULL') return '';
            if (strlen($s) >= 2 && $s[0] === "'" && $s[strlen($s) - 1] === "'") {
                return str_replace("\\'", "'", substr($s, 1, -1));
            }
            return $s;
        };

        $users[] = [
            'didar_user_id' => $unq($fields[1]),
            'email' => $unq($fields[2]),
            'display_name' => $unq($fields[5]),
            'username' => $unq($fields[6]),
        ];
    }

    return $users;
}

$root = dirname(__DIR__);
$dumpPath = $root . DIRECTORY_SEPARATOR . 'hanafivi_didash (1).sql';
$outDir = $root . DIRECTORY_SEPARATOR . 'output';

if (!is_file($dumpPath)) {
    fwrite(STDERR, "Dump not found: $dumpPath\n");
    exit(1);
}

$sqlText = file_get_contents($dumpPath);
$users = parseUserRowsFromDump($sqlText);
if (!$users) {
    fwrite(STDERR, "Could not parse users from dump.\n");
    exit(1);
}

if (!is_dir($outDir)) {
    mkdir($outDir, 0777, true);
}

$csv = "email,username,display_name,new_password\n";
$sqlOut = "SET NAMES utf8mb4;\nSTART TRANSACTION;\n";

foreach ($users as $u) {
    if (empty($u['didar_user_id'])) continue;
    $pw = randPass(14);
    $hash = password_hash($pw, PASSWORD_DEFAULT);
    $csv .= implode(',', [
        normCsv($u['email'] ?? ''),
        normCsv($u['username'] ?? ''),
        normCsv($u['display_name'] ?? ''),
        $pw,
    ]) . "\n";
    $sqlOut .= "UPDATE `users` SET `password`=" . sqlQuote($hash) . " WHERE `didar_user_id`=" . sqlQuote($u['didar_user_id']) . ";\n";
}

$sqlOut .= "COMMIT;\n";

file_put_contents($outDir . DIRECTORY_SEPARATOR . 'reset_all_user_passwords.sql', $sqlOut);
file_put_contents($outDir . DIRECTORY_SEPARATOR . 'reset_all_user_passwords.csv', $csv);

echo "Wrote: output/reset_all_user_passwords.sql\n";
echo "Wrote: output/reset_all_user_passwords.csv\n";

