<?php
declare(strict_types=1);

/**
 * One-time installer. Creates database `crm`, tables, and demo data.
 * Run: C:\xampp\php\php.exe install.php
 * Or open: http://localhost/crm/Staff-Portal/install.php
 */
$base = __DIR__;
require $base . '/app/init.php';

$lock = STORAGE_PATH . '/installed.lock';
if (is_file($lock) && !in_array('--force', $argv ?? [], true)) {
    echo "Already installed. Delete storage/installed.lock or pass --force to reinstall.\n";
    exit(0);
}

$cfg = config();
$host = $cfg['db']['host'];
$port = $cfg['db']['port'] ?? 3306;
$name = $cfg['db']['name'];
$user = $cfg['db']['user'];
$pass = $cfg['db']['pass'];

$pdo = new PDO("mysql:host={$host};port={$port};charset=utf8mb4", $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec("DROP DATABASE IF EXISTS `$name`");
$pdo->exec("CREATE DATABASE `$name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
$pdo->exec("USE `$name`");

$sql = file_get_contents($base . '/sql/schema.sql');
foreach (explode(';', $sql) as $statement) {
    $statement = trim($statement);
    if ($statement === '' || str_starts_with($statement, '--')) {
        continue;
    }
    $pdo->exec($statement);
}

$hash = password_hash('Welcome1!', PASSWORD_DEFAULT);
require $base . '/sql/seed_demo.php';
require $base . '/sql/seed_phase4.php';

file_put_contents($lock, date('c'));
echo "Installed database `$name` with demo records for every section.\n";
echo "Sign in at /crm/Staff-Portal/login  (password Welcome1! for all)\n";
echo "  john.manager@aosware.local   manager + salesperson\n";
echo "  jane.rep@aosware.local       salesperson (full lists / pagination)\n";
echo "  priya.patel@aosware.local    salesperson (West)\n";
echo "  marcus.webb@aosware.local    salesperson (Central)\n";
echo "  admin@aosware.local          admin\n";
echo "  sam.service@aosware.local    service\n";
echo "  maya.chen@aosware.local      marketing (campaigns, lists, templates)\n";
echo "  owen.blake@aosware.local     inactive (Users page)\n";
