<?php
/**
 * God's Treat — one-click cPanel installer.
 * Visit this file once in your browser (yourdomain.com/install.php), fill the form,
 * then DELETE this file from your server.
 */

session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');

function gt_find_app_root(): ?string
{
    $candidates = [
        __DIR__ . '/..',
        __DIR__ . '/../laravel_app',
        __DIR__ . '/../../laravel_app',
    ];
    foreach ($candidates as $path) {
        $real = realpath($path);
        if ($real && is_file($real . '/bootstrap/app.php') && is_dir($real . '/vendor')) {
            return $real;
        }
    }
    $parent = realpath(__DIR__ . '/..');
    if ($parent) {
        foreach ((glob($parent . '/*', GLOB_ONLYDIR) ?: []) as $dir) {
            if (is_file($dir . '/bootstrap/app.php') && is_dir($dir . '/vendor')) {
                return $dir;
            }
        }
    }
    return null;
}

function gt_recursive_copy(string $src, string $dst): void
{
    if (!is_dir($src)) {
        @mkdir($dst, 0755, true);
        return;
    }
    @mkdir($dst, 0755, true);
    foreach (scandir($src) as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }
        $s = $src . '/' . $item;
        $d = $dst . '/' . $item;
        if (is_dir($s)) {
            gt_recursive_copy($s, $d);
        } else {
            @copy($s, $d);
        }
    }
}

function gt_requirements(string $appRoot): array
{
    $checks = [];
    $checks[] = ['label' => 'PHP version >= 8.2', 'ok' => version_compare(PHP_VERSION, '8.2.0', '>='), 'detail' => PHP_VERSION];

    foreach (['openssl', 'pdo', 'mbstring', 'tokenizer', 'xml', 'ctype', 'json', 'bcmath', 'fileinfo', 'curl'] as $ext) {
        $checks[] = ['label' => "PHP extension: $ext", 'ok' => extension_loaded($ext), 'detail' => extension_loaded($ext) ? 'loaded' : 'MISSING'];
    }

    foreach (['storage', 'storage/framework', 'storage/framework/cache', 'storage/framework/sessions', 'storage/framework/views', 'storage/logs', 'storage/app', 'bootstrap/cache'] as $p) {
        $full = $appRoot . '/' . $p;
        $ok = is_dir($full) && is_writable($full);
        $checks[] = ['label' => "Writable: $p", 'ok' => $ok, 'detail' => is_dir($full) ? ($ok ? 'writable' : 'NOT WRITABLE') : 'MISSING FOLDER'];
    }

    $checks[] = ['label' => '.env location writable', 'ok' => is_writable($appRoot), 'detail' => is_writable($appRoot) ? 'ok' : 'NOT WRITABLE'];

    return $checks;
}

$appRoot = gt_find_app_root();

if (!$appRoot) {
    http_response_code(500);
    echo '<!doctype html><html><head><meta charset="utf-8"><title>Installer Error</title></head>'
        . '<body style="font-family:sans-serif;background:#0a0a14;color:#eee;padding:60px;text-align:center">'
        . '<h2 style="color:#f72585">Could not locate the Laravel application folder.</h2>'
        . '<p>Make sure the <code>laravel_app</code> folder sits right next to this file, or this file '
        . 'sits inside <code>laravel_app/public</code>. See DEPLOY_INSTRUCTIONS.txt for the exact folder layout.</p>'
        . '</body></html>';
    exit;
}

$lockFile = $appRoot . '/storage/installed.lock';

if (file_exists($lockFile)) {
    http_response_code(403);
    echo '<!doctype html><html><head><meta charset="utf-8"><title>Already Installed</title></head>'
        . '<body style="font-family:sans-serif;background:#0a0a14;color:#eee;display:flex;align-items:center;'
        . 'justify-content:center;min-height:100vh;margin:0;padding:20px">'
        . '<div style="background:#14141f;border:1px solid #2a2a3a;border-radius:16px;padding:40px;max-width:520px;text-align:center">'
        . '<h1 style="color:#ff6b1a">Already Installed</h1>'
        . '<p>This site has already been installed. For security, delete <code>install.php</code> from your server now.</p>'
        . '<p style="color:#9a9aa8;font-size:.85rem">To re-run the installer on purpose, delete <code>storage/installed.lock</code> first. '
        . 'This will NOT erase your existing data — migrations and seeders are safe to re-run.</p>'
        . '</div></body></html>';
    exit;
}

$requirements = gt_requirements($appRoot);
$requirementsPass = !in_array(false, array_column($requirements, 'ok'), true);

$errors = [];
$success = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $requirementsPass) {
    $appName    = trim($_POST['app_name'] ?? "God's Treat");
    $appUrl     = rtrim(trim($_POST['app_url'] ?? ''), '/');
    $dbConn     = $_POST['db_connection'] ?? 'mysql';
    $dbHost     = trim($_POST['db_host'] ?? '127.0.0.1');
    $dbPort     = trim($_POST['db_port'] ?? '3306');
    $dbName     = trim($_POST['db_database'] ?? '');
    $dbUser     = trim($_POST['db_username'] ?? '');
    $dbPass     = (string) ($_POST['db_password'] ?? '');
    $adminName  = trim($_POST['admin_name'] ?? 'Admin');
    $adminEmail = trim($_POST['admin_email'] ?? '');
    $adminPass  = (string) ($_POST['admin_password'] ?? '');
    $rzpKey     = trim($_POST['rzp_key'] ?? '');
    $rzpSecret  = trim($_POST['rzp_secret'] ?? '');
    $mailHost   = trim($_POST['mail_host'] ?? '');
    $mailUser   = trim($_POST['mail_username'] ?? '');
    $mailPass   = (string) ($_POST['mail_password'] ?? '');
    $mailFrom   = trim($_POST['mail_from'] ?? '');

    if ($appUrl === '') {
        $errors[] = 'Site URL is required.';
    }
    if (!filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'A valid admin email is required.';
    }
    if (strlen($adminPass) < 8) {
        $errors[] = 'Admin password must be at least 8 characters.';
    }

    if ($dbConn === 'mysql') {
        if ($dbName === '' || $dbUser === '') {
            $errors[] = 'Database name and username are required for MySQL.';
        }
        if (!$errors) {
            try {
                $dsn = "mysql:host=$dbHost;port=$dbPort;dbname=$dbName;charset=utf8mb4";
                new PDO($dsn, $dbUser, $dbPass, [PDO::ATTR_TIMEOUT => 5]);
            } catch (\Throwable $e) {
                $errors[] = 'Could not connect to the MySQL database: ' . $e->getMessage();
            }
        }
    }

    if (!$errors) {
        try {
            $appKey = 'base64:' . base64_encode(random_bytes(32));
            $env = [];
            $env[] = 'APP_NAME="' . addslashes($appName) . '"';
            $env[] = 'APP_ENV=production';
            $env[] = 'APP_KEY=' . $appKey;
            $env[] = 'APP_DEBUG=false';
            $env[] = 'APP_URL=' . $appUrl;
            $env[] = '';
            $env[] = 'APP_LOCALE=en';
            $env[] = 'APP_FALLBACK_LOCALE=en';
            $env[] = 'APP_FAKER_LOCALE=en_US';
            $env[] = '';
            $env[] = 'APP_MAINTENANCE_DRIVER=file';
            $env[] = 'BCRYPT_ROUNDS=12';
            $env[] = '';
            $env[] = 'LOG_CHANNEL=stack';
            $env[] = 'LOG_STACK=single';
            $env[] = 'LOG_DEPRECATIONS_CHANNEL=null';
            $env[] = 'LOG_LEVEL=error';
            $env[] = '';

            if ($dbConn === 'mysql') {
                $env[] = 'DB_CONNECTION=mysql';
                $env[] = 'DB_HOST=' . $dbHost;
                $env[] = 'DB_PORT=' . $dbPort;
                $env[] = 'DB_DATABASE=' . $dbName;
                $env[] = 'DB_USERNAME=' . $dbUser;
                $env[] = 'DB_PASSWORD=' . $dbPass;
            } else {
                $sqlitePath = $appRoot . '/database/database.sqlite';
                if (!file_exists($sqlitePath)) {
                    touch($sqlitePath);
                }
                $env[] = 'DB_CONNECTION=sqlite';
                $env[] = 'DB_DATABASE=' . $sqlitePath;
            }

            $env[] = '';
            $env[] = 'SESSION_DRIVER=database';
            $env[] = 'SESSION_LIFETIME=120';
            $env[] = 'SESSION_ENCRYPT=false';
            $env[] = 'SESSION_PATH=/';
            $env[] = 'SESSION_DOMAIN=null';
            $env[] = '';
            $env[] = 'BROADCAST_CONNECTION=log';
            $env[] = 'FILESYSTEM_DISK=local';
            $env[] = 'QUEUE_CONNECTION=database';
            $env[] = 'CACHE_STORE=database';
            $env[] = '';
            $env[] = 'MAIL_MAILER=' . ($mailHost !== '' ? 'smtp' : 'log');
            $env[] = 'MAIL_HOST=' . ($mailHost !== '' ? $mailHost : '127.0.0.1');
            $env[] = 'MAIL_PORT=587';
            $env[] = 'MAIL_USERNAME=' . $mailUser;
            $env[] = 'MAIL_PASSWORD=' . $mailPass;
            $env[] = 'MAIL_FROM_ADDRESS="' . ($mailFrom !== '' ? $mailFrom : 'orders@example.com') . '"';
            $env[] = 'MAIL_FROM_NAME="${APP_NAME}"';
            $env[] = '';
            $env[] = 'RAZORPAY_KEY=' . $rzpKey;
            $env[] = 'RAZORPAY_SECRET=' . $rzpSecret;
            $env[] = '';
            $env[] = 'VITE_APP_NAME="${APP_NAME}"';

            file_put_contents($appRoot . '/.env', implode("\n", $env) . "\n");

            require $appRoot . '/vendor/autoload.php';
            $app = require $appRoot . '/bootstrap/app.php';
            $kernel = $app->make(\Illuminate\Contracts\Console\Kernel::class);
            $kernel->bootstrap();

            \Illuminate\Support\Facades\Artisan::call('migrate', ['--force' => true]);
            \Illuminate\Support\Facades\Artisan::call('db:seed', ['--force' => true]);

            \App\Models\User::updateOrCreate(
                ['email' => $adminEmail],
                [
                    'name'     => $adminName,
                    'password' => \Illuminate\Support\Facades\Hash::make($adminPass),
                    'is_admin' => true,
                ]
            );

            $target = $appRoot . '/storage/app/public';
            $link   = __DIR__ . '/storage';
            if (!file_exists($link)) {
                $linked = function_exists('symlink') ? @symlink($target, $link) : false;
                if (!$linked) {
                    gt_recursive_copy($target, $link);
                }
            }

            \Illuminate\Support\Facades\Artisan::call('config:clear');
            \Illuminate\Support\Facades\Artisan::call('cache:clear');
            \Illuminate\Support\Facades\Artisan::call('view:clear');
            \Illuminate\Support\Facades\Artisan::call('route:clear');

            file_put_contents($lockFile, date('c'));

            $success = ['url' => $appUrl, 'email' => $adminEmail];
        } catch (\Throwable $e) {
            $errors[] = 'Installation failed: ' . $e->getMessage();
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Install &mdash; God's Treat</title>
<style>
  * { box-sizing: border-box; }
  body { margin:0; font-family: -apple-system, Segoe UI, Roboto, sans-serif; background:#0a0a14; color:#f0f0f5; padding:40px 16px; }
  .wrap { max-width: 720px; margin: 0 auto; }
  .logo { font-size:1.6rem; font-weight:800; color:#ff6b1a; margin-bottom:4px; }
  .sub { color:#9a9aa8; margin-bottom:28px; }
  .card { background:#14141f; border:1px solid #2a2a3a; border-radius:16px; padding:28px; margin-bottom:20px; }
  h2 { margin-top:0; font-size:1.15rem; color:#fff; }
  .req-item { display:flex; justify-content:space-between; padding:8px 0; border-bottom:1px solid #22222f; font-size:.88rem; }
  .req-item:last-child { border-bottom:none; }
  .ok { color:#06d6a0; font-weight:700; }
  .bad { color:#f72585; font-weight:700; }
  label { display:block; font-size:.78rem; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:#9a9aa8; margin-bottom:6px; margin-top:16px; }
  input, select { width:100%; background:#1c1c2a; border:1px solid #33334a; color:#fff; padding:11px 14px; border-radius:10px; font-size:.9rem; }
  input:focus, select:focus { outline:none; border-color:#ff6b1a; }
  .row { display:grid; grid-template-columns:1fr 1fr; gap:16px; }
  button { background:linear-gradient(135deg,#ff6b1a,#ff8c42); border:none; color:#0a0a14; font-weight:800; padding:14px 28px; border-radius:10px; font-size:1rem; cursor:pointer; margin-top:24px; width:100%; }
  button:hover { opacity:.92; }
  .err-box { background:rgba(247,37,133,.1); border:1px solid rgba(247,37,133,.3); color:#ff8fb8; padding:14px 18px; border-radius:10px; margin-bottom:20px; font-size:.88rem; }
  .success-box { background:rgba(6,214,160,.1); border:1px solid rgba(6,214,160,.3); color:#06d6a0; padding:24px; border-radius:16px; text-align:center; }
  .hint { font-size:.76rem; color:#75758a; margin-top:4px; }
  a { color:#ff6b1a; }
  .db-panel { display:none; }
  .db-panel.active { display:block; }
</style>
</head>
<body>
<div class="wrap">
  <div class="logo">GOD'S TREAT</div>
  <div class="sub">One-click installer &mdash; configures the database, admin account &amp; storage in one go.</div>

  <?php if ($success): ?>
    <div class="card">
      <div class="success-box">
        <h2 style="color:#06d6a0">Installed successfully!</h2>
        <p>Your store is live at <a href="<?= htmlspecialchars($success['url']) ?>" target="_blank"><?= htmlspecialchars($success['url']) ?></a></p>
        <p>Admin login: <strong><?= htmlspecialchars($success['email']) ?></strong> (password you just set)</p>
        <p style="margin-top:18px"><a href="<?= htmlspecialchars($success['url']) ?>/login">&rarr; Go to Login</a></p>
      </div>
      <div class="err-box" style="margin-top:20px;color:#ffd166;background:rgba(255,209,102,.1);border-color:rgba(255,209,102,.3)">
        <strong>Important:</strong> Delete <code>install.php</code> from your server now (File Manager &rarr; delete this file). Leaving it live lets anyone re-run it.
      </div>
    </div>
  <?php else: ?>

    <?php if ($errors): ?>
      <div class="err-box">
        <strong>Please fix the following:</strong>
        <ul style="margin:8px 0 0 18px;padding:0">
          <?php foreach ($errors as $e): ?><li><?= htmlspecialchars($e) ?></li><?php endforeach; ?>
        </ul>
      </div>
    <?php endif; ?>

    <div class="card">
      <h2>1. Server Requirements</h2>
      <?php foreach ($requirements as $r): ?>
        <div class="req-item">
          <span><?= htmlspecialchars($r['label']) ?></span>
          <span class="<?= $r['ok'] ? 'ok' : 'bad' ?>"><?= $r['ok'] ? '&#10003; ' : '&#10007; ' ?><?= htmlspecialchars($r['detail']) ?></span>
        </div>
      <?php endforeach; ?>
      <?php if (!$requirementsPass): ?>
        <div class="err-box" style="margin-top:16px">Fix the items marked &#10007; above (ask your host to enable missing PHP extensions, or fix folder permissions to 755), then reload this page.</div>
      <?php endif; ?>
    </div>

    <?php if ($requirementsPass): ?>
    <form method="POST">
      <div class="card">
        <h2>2. Site Settings</h2>
        <label>Store Name</label>
        <input type="text" name="app_name" value="<?= htmlspecialchars($_POST['app_name'] ?? "God's Treat") ?>" required>
        <label>Site URL (no trailing slash)</label>
        <input type="text" name="app_url" placeholder="https://yourdomain.com" value="<?= htmlspecialchars($_POST['app_url'] ?? '') ?>" required>
        <div class="hint">Example: https://godstreat.in &mdash; do not add a trailing slash.</div>
      </div>

      <div class="card">
        <h2>3. Database</h2>
        <label>Database Type</label>
        <select name="db_connection" id="dbConn" onchange="gtToggleDb()">
          <option value="mysql" <?= ($_POST['db_connection'] ?? 'mysql') === 'mysql' ? 'selected' : '' ?>>MySQL (recommended for cPanel)</option>
          <option value="sqlite" <?= ($_POST['db_connection'] ?? '') === 'sqlite' ? 'selected' : '' ?>>SQLite (simple / low traffic)</option>
        </select>

        <div id="mysqlPanel" class="db-panel">
          <div class="row">
            <div><label>DB Host</label><input type="text" name="db_host" value="<?= htmlspecialchars($_POST['db_host'] ?? '127.0.0.1') ?>"></div>
            <div><label>DB Port</label><input type="text" name="db_port" value="<?= htmlspecialchars($_POST['db_port'] ?? '3306') ?>"></div>
          </div>
          <label>Database Name</label>
          <input type="text" name="db_database" placeholder="cpaneluser_godstreat" value="<?= htmlspecialchars($_POST['db_database'] ?? '') ?>">
          <div class="row">
            <div><label>DB Username</label><input type="text" name="db_username" placeholder="cpaneluser_dbuser" value="<?= htmlspecialchars($_POST['db_username'] ?? '') ?>"></div>
            <div><label>DB Password</label><input type="password" name="db_password" value="<?= htmlspecialchars($_POST['db_password'] ?? '') ?>"></div>
          </div>
          <div class="hint">Create this database + user first from cPanel &rarr; MySQL Databases, then add the user to the database with ALL PRIVILEGES.</div>
        </div>
      </div>

      <div class="card">
        <h2>4. Admin Account</h2>
        <label>Your Name</label>
        <input type="text" name="admin_name" value="<?= htmlspecialchars($_POST['admin_name'] ?? '') ?>" required>
        <label>Admin Email (this is your login)</label>
        <input type="email" name="admin_email" value="<?= htmlspecialchars($_POST['admin_email'] ?? '') ?>" required>
        <label>Admin Password (min 8 characters)</label>
        <input type="password" name="admin_password" required minlength="8">
      </div>

      <div class="card">
        <h2>5. Payments &amp; Email <span style="color:#75758a;font-weight:400;font-size:.8rem">(optional &mdash; can be added later)</span></h2>
        <div class="row">
          <div><label>Razorpay Key ID</label><input type="text" name="rzp_key" value="<?= htmlspecialchars($_POST['rzp_key'] ?? '') ?>"></div>
          <div><label>Razorpay Secret</label><input type="text" name="rzp_secret" value="<?= htmlspecialchars($_POST['rzp_secret'] ?? '') ?>"></div>
        </div>
        <label>SMTP Host</label>
        <input type="text" name="mail_host" placeholder="smtp.gmail.com" value="<?= htmlspecialchars($_POST['mail_host'] ?? '') ?>">
        <div class="row">
          <div><label>SMTP Username</label><input type="text" name="mail_username" value="<?= htmlspecialchars($_POST['mail_username'] ?? '') ?>"></div>
          <div><label>SMTP Password</label><input type="password" name="mail_password" value=""></div>
        </div>
        <label>"From" Email Address</label>
        <input type="email" name="mail_from" placeholder="orders@yourdomain.com" value="<?= htmlspecialchars($_POST['mail_from'] ?? '') ?>">
      </div>

      <button type="submit">Install Now</button>
    </form>
    <?php endif; ?>
  <?php endif; ?>
</div>
<script>
function gtToggleDb() {
  var v = document.getElementById('dbConn').value;
  document.getElementById('mysqlPanel').classList.toggle('active', v === 'mysql');
}
gtToggleDb();
</script>
</body>
</html>
