<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

$scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
$baseUrl = ($scriptDir !== '/' && $scriptDir !== '\\') ? rtrim($scriptDir, '/') : '';

$parentDir = dirname(__DIR__);
$privatePath = null;
$searchPaths = [
    $parentDir . '/private',
    $parentDir . '/ganadera_private',
    dirname($parentDir) . '/private',
    dirname($parentDir) . '/ganadera_private',
    __DIR__ . '/../private',
    __DIR__ . '/private',
];
foreach ($searchPaths as $p) {
    if (is_dir($p) && file_exists($p . '/database/schema.sql')) {
        $privatePath = realpath($p);
        break;
    }
}

$isInstalled = $privatePath && file_exists($privatePath . '/config/installed.php');
$step = $_POST['step'] ?? $_GET['step'] ?? 'requirements';
if ($isInstalled && $step !== 'permissions') {
    header('Location: ' . ($baseUrl ?: '/'));
    exit;
}

$error = null;
$success = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step === 'database') {
    $result = handleInstall($privatePath);
    if ($result === true) {
        $step = 'complete';
    } else {
        $error = $result;
        $step = 'database';
    }
}

$requirements = getRequirements($privatePath);
$allPassed = true;
foreach ($requirements as $r) {
    if (!$r['status']) { $allPassed = false; break; }
}

ensureDirs($privatePath);

function getRequirements($privatePath) {
    $r = [];
    $r[] = ['name' => 'PHP 8.0+', 'status' => version_compare(PHP_VERSION, '8.0.0', '>='), 'current' => PHP_VERSION];
    $r[] = ['name' => 'PDO MySQL', 'status' => extension_loaded('pdo_mysql'), 'current' => extension_loaded('pdo_mysql') ? 'OK' : 'No'];
    $r[] = ['name' => 'mbstring', 'status' => extension_loaded('mbstring'), 'current' => extension_loaded('mbstring') ? 'OK' : 'No'];
    $r[] = ['name' => 'GD/Imagick', 'status' => extension_loaded('gd') || extension_loaded('imagick'), 'current' => extension_loaded('gd') ? 'GD' : (extension_loaded('imagick') ? 'Imagick' : 'No')];
    $r[] = ['name' => 'JSON', 'status' => extension_loaded('json'), 'current' => extension_loaded('json') ? 'OK' : 'No'];
    $r[] = ['name' => 'Dir privado', 'status' => $privatePath !== null, 'current' => $privatePath ? basename($privatePath) : 'No encontrado'];
    $uploadsOk = is_dir(__DIR__ . '/uploads') && is_writable(__DIR__ . '/uploads');
    $r[] = ['name' => 'Dir uploads', 'status' => $uploadsOk, 'current' => $uploadsOk ? 'OK' : 'Sin permisos'];
    if ($privatePath) {
        $schemaOk = file_exists($privatePath . '/database/schema.sql');
        $r[] = ['name' => 'schema.sql', 'status' => $schemaOk, 'current' => $schemaOk ? 'OK' : 'No encontrado'];
    }
    return $r;
}

function ensureDirs($privatePath) {
    $dirs = [__DIR__ . '/uploads', __DIR__ . '/uploads/photos', __DIR__ . '/uploads/evidence', __DIR__ . '/uploads/documents'];
    if ($privatePath) {
        $dirs[] = $privatePath . '/storage';
        $dirs[] = $privatePath . '/storage/logs';
        $dirs[] = $privatePath . '/storage/cache';
        $dirs[] = $privatePath . '/storage/temp';
        $dirs[] = $privatePath . '/config';
    }
    foreach ($dirs as $d) {
        if (!is_dir($d)) @mkdir($d, 0775, true);
        if (is_dir($d)) @chmod($d, 0775);
    }
}

function handleInstall($privatePath) {
    if (!$privatePath) return 'No se encontro el directorio privado.';
    $dbHost = trim($_POST['db_host'] ?? 'localhost');
    $dbPort = intval($_POST['db_port'] ?? 3306);
    $dbName = trim($_POST['db_name'] ?? '');
    $dbUser = trim($_POST['db_user'] ?? '');
    $dbPass = $_POST['db_pass'] ?? '';
    $appUrl = rtrim(trim($_POST['app_url'] ?? ''), '/');
    $ranchName = trim($_POST['ranch_name'] ?? 'Mi Rancho');
    $adminUser = trim($_POST['admin_user'] ?? 'admin');
    $adminEmail = trim($_POST['admin_email'] ?? '');
    $adminPass = $_POST['admin_pass'] ?? '';

    if (empty($dbName)) return 'Nombre de BD obligatorio.';
    if (empty($dbUser)) return 'Usuario de BD obligatorio.';
    if (empty($appUrl)) return 'URL obligatoria.';
    if (empty($adminUser)) return 'Usuario admin obligatorio.';
    if (empty($adminEmail)) return 'Email admin obligatorio.';
    if (empty($adminPass) || strlen($adminPass) < 6) return 'Contrasena minimo 6 caracteres.';

    try {
        $dsn = "mysql:host=$dbHost;port=$dbPort;charset=utf8mb4";
        $pdo = new PDO($dsn, $dbUser, $dbPass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    } catch (PDOException $e) {
        return 'Error de conexion: ' . $e->getMessage();
    }

    try {
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
        $pdo->exec("USE `$dbName`");
    } catch (PDOException $e) {
        return 'Error creando BD: ' . $e->getMessage();
    }

    $schemaFile = $privatePath . '/database/schema.sql';
    if (!file_exists($schemaFile)) return 'schema.sql no encontrado.';
    try {
        $pdo->exec(file_get_contents($schemaFile));
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'already exists') === false) {
            return 'Error creando tablas: ' . $e->getMessage();
        }
    }

    $seedsFile = $privatePath . '/database/seeds.sql';
    if (file_exists($seedsFile)) {
        try { $pdo->exec(file_get_contents($seedsFile)); } catch (PDOException $e) {}
    }

    try {
        $hash = password_hash($adminPass, PASSWORD_BCRYPT, ['cost' => 12]);
        $roleRow = $pdo->query("SELECT id FROM roles WHERE slug = 'superadmin' LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        $roleId = $roleRow['id'] ?? 1;
        $exists = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $exists->execute([$adminUser]);
        $row = $exists->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $st = $pdo->prepare("UPDATE users SET password_hash = ?, email = ?, is_active = 1 WHERE id = ?");
            $st->execute([$hash, $adminEmail, $row['id']]);
        } else {
            $st = $pdo->prepare("INSERT INTO users (role_id, username, email, password_hash, first_name, last_name, is_active) VALUES (?, ?, ?, ?, ?, ?, 1)");
            $st->execute([$roleId, $adminUser, $adminEmail, $hash, ucfirst($adminUser), 'Admin']);
        }
        try {
            $st = $pdo->prepare("INSERT INTO app_settings (ranch_id, setting_key, setting_value) VALUES (1, 'ranch_name', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
            $st->execute([$ranchName]);
        } catch (PDOException $e) {}
    } catch (PDOException $e) {
        return 'Error creando admin: ' . $e->getMessage();
    }

    $jwt = bin2hex(random_bytes(32));
    $cfg = "<?php\nreturn [\n"
        . "    'db_host' => " . var_export($dbHost, true) . ",\n"
        . "    'db_port' => " . var_export($dbPort, true) . ",\n"
        . "    'db_name' => " . var_export($dbName, true) . ",\n"
        . "    'db_user' => " . var_export($dbUser, true) . ",\n"
        . "    'db_pass' => " . var_export($dbPass, true) . ",\n"
        . "    'app_url' => " . var_export($appUrl, true) . ",\n"
        . "    'jwt_secret' => " . var_export($jwt, true) . ",\n"
        . "    'ranch_name' => " . var_export($ranchName, true) . ",\n"
        . "    'installed_at' => " . var_export(date('Y-m-d H:i:s'), true) . ",\n"
        . "];\n";

    $cfgDir = $privatePath . '/config';
    if (!is_dir($cfgDir)) mkdir($cfgDir, 0755, true);
    if (file_put_contents($cfgDir . '/installed.php', $cfg) === false) {
        return 'No se pudo escribir installed.php. Verifica permisos en ' . $cfgDir;
    }

    ensureDirs($privatePath);
    return true;
}

$postDbHost = htmlspecialchars($_POST['db_host'] ?? 'localhost', ENT_QUOTES, 'UTF-8');
$postDbPort = htmlspecialchars($_POST['db_port'] ?? '3306', ENT_QUOTES, 'UTF-8');
$postDbName = htmlspecialchars($_POST['db_name'] ?? '', ENT_QUOTES, 'UTF-8');
$postDbUser = htmlspecialchars($_POST['db_user'] ?? '', ENT_QUOTES, 'UTF-8');
$postDbPass = htmlspecialchars($_POST['db_pass'] ?? '', ENT_QUOTES, 'UTF-8');
$defaultUrl = 'https://' . ($_SERVER['HTTP_HOST'] ?? 'tu-dominio.com') . $baseUrl;
$postAppUrl = htmlspecialchars($_POST['app_url'] ?? $defaultUrl, ENT_QUOTES, 'UTF-8');
$postRanchName = htmlspecialchars($_POST['ranch_name'] ?? 'Mi Rancho', ENT_QUOTES, 'UTF-8');
$postAdminUser = htmlspecialchars($_POST['admin_user'] ?? 'admin', ENT_QUOTES, 'UTF-8');
$postAdminEmail = htmlspecialchars($_POST['admin_email'] ?? '', ENT_QUOTES, 'UTF-8');

$stepDot1 = ($step === 'requirements') ? 'active' : 'done';
$stepDot2 = ($step === 'database') ? 'active' : (($step === 'complete') ? 'done' : '');
$stepDot3 = ($step === 'complete') ? 'active' : '';
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Instalador - Plataforma Ganadera</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="install.css">
</head>
<body>
<div class="loading-overlay" id="loadingOverlay">
<div class="loading-box">
<div class="spinner"></div>
<p class="loading-title">Instalando...</p>
<p class="loading-sub">Creando tablas y configuracion</p>
</div>
</div>
<div class="installer">
<div class="installer-header">
<div class="logo">PG</div>
<h1>Plataforma Ganadera</h1>
<p>Asistente de instalacion</p>
</div>
<div class="steps">
<div class="step-dot <?php echo $stepDot1; ?>"></div>
<div class="step-dot <?php echo $stepDot2; ?>"></div>
<div class="step-dot <?php echo $stepDot3; ?>"></div>
</div>
<div class="installer-body">
<?php if ($error): ?>
<div class="alert alert-error"><span>(!)</span> <span><?php echo htmlspecialchars($error); ?></span></div>
<?php endif; ?>

<?php if ($step === 'requirements'): ?>
<div class="section-title"><div class="icon">1</div> Verificacion de requisitos</div>
<table class="req-table">
<?php foreach ($requirements as $req): ?>
<tr>
<td><?php echo htmlspecialchars($req['name']); ?></td>
<td><?php echo htmlspecialchars($req['current']); ?></td>
<td><span class="badge <?php echo $req['status'] ? 'badge-ok' : 'badge-fail'; ?>"><?php echo $req['status'] ? 'OK' : 'Error'; ?></span></td>
</tr>
<?php endforeach; ?>
</table>
<?php if (!$allPassed): ?>
<div class="alert alert-warning alert-mt"><span>(!)</span> <span>Algunos requisitos no se cumplen.</span></div>
<?php endif; ?>
<div class="btn-row"><a href="?step=database" class="btn btn-primary">Continuar &rarr;</a></div>

<?php elseif ($step === 'database'): ?>
<form method="POST" id="installForm" autocomplete="off">
<input type="hidden" name="step" value="database">
<div class="section-title"><div class="icon">2</div> Configuracion</div>
<div class="alert alert-warning"><span>*</span> <span>Crea primero la BD y usuario en cPanel.</span></div>
<div class="form-grid">
<div class="form-group"><label>Servidor MySQL</label><input type="text" name="db_host" value="<?php echo $postDbHost; ?>" required><span class="form-hint">Generalmente localhost</span></div>
<div class="form-group"><label>Puerto</label><input type="number" name="db_port" value="<?php echo $postDbPort; ?>" required></div>
<div class="form-group"><label>Base de datos</label><input type="text" name="db_name" value="<?php echo $postDbName; ?>" required placeholder="usuario_ganadera"></div>
<div class="form-group"><label>Usuario BD</label><input type="text" name="db_user" value="<?php echo $postDbUser; ?>" required placeholder="usuario_dbuser"></div>
<div class="form-group full-width"><label>Contrasena BD</label><input type="password" name="db_pass" value="<?php echo $postDbPass; ?>"></div>
<hr class="form-separator">
<div class="form-section-label">Configuracion del sitio</div>
<div class="form-group full-width"><label>URL</label><input type="url" name="app_url" value="<?php echo $postAppUrl; ?>" required></div>
<div class="form-group full-width"><label>Nombre del rancho</label><input type="text" name="ranch_name" value="<?php echo $postRanchName; ?>" required></div>
<hr class="form-separator">
<div class="form-section-label">Usuario administrador</div>
<div class="form-group"><label>Usuario</label><input type="text" name="admin_user" value="<?php echo $postAdminUser; ?>" required autocomplete="off"></div>
<div class="form-group"><label>Email</label><input type="email" name="admin_email" value="<?php echo $postAdminEmail; ?>" required autocomplete="off"></div>
<div class="form-group full-width"><label>Contrasena</label><input type="password" name="admin_pass" required minlength="6" autocomplete="new-password" placeholder="Minimo 6 caracteres"></div>
</div>
<div class="btn-row">
<a href="?step=requirements" class="btn btn-secondary">&larr; Atras</a>
<button type="submit" class="btn btn-primary" id="btnInstall">Instalar</button>
</div>
</form>

<?php elseif ($step === 'complete'): ?>
<div class="complete-screen">
<div class="complete-icon">&#10004;</div>
<h2>Instalacion completada</h2>
<p>La Plataforma Ganadera se instalo correctamente.</p>
<div class="credentials-box">
<div class="cred-label">Datos de acceso:</div>
<div class="cred-row"><span>Usuario:</span> <span><?php echo htmlspecialchars($_POST['admin_user'] ?? 'admin'); ?></span></div>
<div class="cred-row"><span>Email:</span> <span><?php echo htmlspecialchars($_POST['admin_email'] ?? ''); ?></span></div>
</div>
<div class="complete-warning"><strong>IMPORTANTE:</strong> Elimina install.php del servidor por seguridad.</div>
<div class="btn-row btn-row-center"><a href="<?php echo $baseUrl ?: '/'; ?>" class="btn btn-primary">Ir a la aplicacion</a></div>
</div>
<?php endif; ?>

</div>
</div>
<script>
var f = document.getElementById('installForm');
if (f) f.addEventListener('submit', function() {
document.getElementById('loadingOverlay').classList.add('active');
document.getElementById('btnInstall').disabled = true;
});
</script>
</body>
</html>
