<?php

// Robust .env parser
function getEnvVar($key, $default = null)
{
    if (! file_exists(__DIR__.'/../.env')) {
        return $default;
    }
    $content = file_get_contents(__DIR__.'/../.env');
    if (preg_match('/^'.preg_quote($key).'=(.*)$/m', $content, $matches)) {
        return trim($matches[1], " \t\n\r\0\x0B\"'");
    }

    return $default;
}

$host = getEnvVar('DB_HOST', '127.0.0.1');
$port = getEnvVar('DB_PORT', '3306');
$db = getEnvVar('DB_DATABASE');
$user = getEnvVar('DB_USERNAME');
$pass = getEnvVar('DB_PASSWORD');

// Fallback for this specific project if .env is missing or unreadable
if (! $db) {
    $db = 'innovaajustes_sis';
}
if (! $user) {
    $user = 'innovaajustes_miideasc';
}
if (! $pass) {
    $pass = 'calidad22EC';
}

try {
    if (! $db || ! $user) {
        throw new Exception('Database credentials not found in .env and fallback failed.');
    }

    $pdo = new PDO("mysql:host=$host;port=$port;dbname=$db;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Changing the ENUM to TEXT to allow JSON array inputs
    $pdo->exec('ALTER TABLE seguimiento_reparaciones MODIFY tipo_trabajo TEXT NULL');

    echo '<h1>Success!</h1><p>The database column has been updated to TEXT. You can now save the repair tracking form.</p>';
} catch (Exception $e) {
    echo '<h1>Connection Error</h1><p>'.$e->getMessage().'</p>';
    echo '<p>Please ensure your .env file has the correct DB_DATABASE, DB_USERNAME, and DB_PASSWORD.</p>';
}
