<?php
/**
 * db-reset.php — one-time database reset helper.
 *
 * WHAT IT DOES:
 *  1. Reads DB_* values straight from your .env file and shows them on screen
 *     (password is masked) so you can visually confirm they're correct.
 *  2. Tests the database connection using those exact values.
 *  3. If connection succeeds, offers a button to drop ALL tables in that
 *     database so the installer can rebuild everything from scratch.
 *
 * HOW TO USE:
 *  1. Upload this file into the SAME folder as your "artisan" file
 *     (the project root, next to install-web.php).
 *  2. Visit it in your browser with the token below appended, e.g.:
 *     https://yourdomain.com/db-reset.php?token=51afe7ca0b64d34a7dbd6d156e498cfc
 *  3. When you're done, DELETE this file from the server. Do not leave it
 *     online — it can permanently erase your database if someone finds the URL.
 */

$TOKEN = '51afe7ca0b64d34a7dbd6d156e498cfc';

$root = __DIR__;

function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES); }

$providedToken = $_GET['token'] ?? '';
if (!hash_equals($TOKEN, $providedToken)) {
    http_response_code(403);
    die('Forbidden. Open this page with ?token=YOUR_TOKEN at the end of the URL.');
}

echo '<!doctype html><html><head><meta charset="utf-8"><title>DB Reset Helper</title>';
echo '<style>body{font-family:sans-serif;max-width:700px;margin:40px auto;padding:0 16px;line-height:1.5}
pre{background:#f4f4f4;padding:12px;border-radius:6px;overflow:auto}
.btn{display:inline-block;padding:10px 18px;border-radius:5px;text-decoration:none;color:#fff}
.btn-danger{background:#c0392b}
.ok{color:#1a7d1a} .err{color:#c0392b}</style></head><body>';
echo '<h1>Database Reset Helper</h1>';

// ---- Step 1: read .env ----
$envPath = $root . '/.env';
if (!file_exists($envPath)) {
    die('<p class="err">.env not found at ' . h($envPath) . '</p></body></html>');
}

$env = [];
foreach (file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
    $line = trim($line);
    if ($line === '' || str_starts_with($line, '#') || strpos($line, '=') === false) continue;
    [$k, $v] = explode('=', $line, 2);
    $k = trim($k);
    $v = trim(trim($v), "\"'");
    $env[$k] = $v;
}

$host = $env['DB_HOST'] ?? 'localhost';
$port = $env['DB_PORT'] ?? '3306';
$db   = $env['DB_DATABASE'] ?? '';
$user = $env['DB_USERNAME'] ?? '';
$pass = $env['DB_PASSWORD'] ?? '';

echo '<h2>1. Current settings read from .env</h2><pre>';
echo 'DB_HOST     = ' . h($host) . "\n";
echo 'DB_PORT     = ' . h($port) . "\n";
echo 'DB_DATABASE = ' . h($db) . "\n";
echo 'DB_USERNAME = ' . h($user) . "\n";
echo 'DB_PASSWORD = ' . (strlen($pass) ? str_repeat('*', strlen($pass)) . ' (' . strlen($pass) . ' characters)' : '(EMPTY!)') . "\n";
echo '</pre>';

if ($user === '' || strpos($user, '@') !== false && strpos($user, '@' . $pass) !== false) {
    echo '<p class="err">Warning: DB_USERNAME looks unusual (contains "@" followed by what looks like a password). Double-check .env before continuing.</p>';
}

// ---- Step 2: test connection ----
echo '<h2>2. Connection test</h2>';
$mysqli = @new mysqli($host, $user, $pass, $db, (int)$port);

if ($mysqli->connect_errno) {
    echo '<p class="err"><strong>Connection FAILED:</strong> ' . h($mysqli->connect_error) . '</p>';
    echo '<p>Fix DB_USERNAME / DB_PASSWORD / DB_DATABASE in .env via cPanel File Manager so they exactly match the user you created under cPanel &raquo; MySQL&reg; Databases, then reload this page.</p>';
    echo '</body></html>';
    exit;
}
echo '<p class="ok"><strong>Connection OK.</strong> The credentials in .env are working.</p>';

// ---- Step 3: show tables / offer drop ----
$result = $mysqli->query('SHOW TABLES');
$tables = [];
while ($row = $result->fetch_array()) $tables[] = $row[0];

echo '<h2>3. Tables currently in "' . h($db) . '"</h2>';
if (empty($tables)) {
    echo '<p class="ok">No tables found — the database is already empty. You can go straight back to the installer and run Step 2 (migrate) now.</p>';
    echo '</body></html>';
    exit;
}
echo '<pre>' . h(implode("\n", $tables)) . '</pre>';

$confirmed = isset($_GET['confirm']) && $_GET['confirm'] === 'yes';

if (!$confirmed) {
    $dropUrl = '?token=' . urlencode($TOKEN) . '&confirm=yes';
    echo '<p><strong>This will permanently delete all ' . count($tables) . ' table(s) above and everything in them.</strong> ';
    echo 'Only do this if the database has no real data yet.</p>';
    echo '<a class="btn btn-danger" href="' . h($dropUrl) . '" onclick="return confirm(\'This permanently deletes ALL data in ' . h($db) . '. Are you sure?\');">Drop all tables now</a>';
    echo '</body></html>';
    exit;
}

// ---- Step 4: actually drop ----
$mysqli->query('SET FOREIGN_KEY_CHECKS = 0');
$dropped = [];
foreach ($tables as $table) {
    if ($mysqli->query('DROP TABLE IF EXISTS `' . $table . '`')) {
        $dropped[] = $table;
    }
}
$mysqli->query('SET FOREIGN_KEY_CHECKS = 1');

echo '<h2>Done</h2>';
echo '<p class="ok">Dropped ' . count($dropped) . ' table(s):</p><pre>' . h(implode("\n", $dropped)) . '</pre>';
echo '<p><strong>Next step:</strong> go back to your installer (install-web.php) and re-run Step 2 to rebuild all tables cleanly.</p>';
echo '<p class="err"><strong>Now delete this file (db-reset.php) from the server — do not leave it online.</strong></p>';
echo '</body></html>';
