<?php
$host = "192.168.0.13";
$dbname = "forza_mqtt2";
$user = "bot";
$password = "Tykun.2026";

// $user = "agtechsr_user";
// $password = "Alefortress8.";
// $host = "72.52.185.80";
// $dbname = "agtechsr_forzam";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Primero, asegurarnos que la columna sea del tipo correcto
    $pdo->exec("ALTER TABLE ups_settings MODIFY COLUMN ups_device_id INT NULL");
    
    // Actualizar registros uno por uno para mejor control
    $stmt = $pdo->query("SELECT s.id, d.id as device_id 
                         FROM ups_settings s 
                         JOIN ups_devices d ON s.person_id = d.person_id");
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $update = $pdo->prepare("UPDATE ups_settings 
                                SET ups_device_id = ? 
                                WHERE id = ?");
        $update->execute([(int)$row['device_id'], $row['id']]);
    }
    
    // Verificar que no haya valores NULL
    $nullCheck = $pdo->query("SELECT COUNT(*) FROM ups_settings WHERE ups_device_id IS NULL");
    if ($nullCheck->fetchColumn() > 0) {
        throw new Exception("Aún hay registros con ups_device_id NULL");
    }
    
    // Ahora sí agregar las restricciones
    $pdo->exec("ALTER TABLE ups_settings 
                MODIFY COLUMN ups_device_id INT NOT NULL,
                ADD CONSTRAINT fk_ups_device 
                FOREIGN KEY (ups_device_id) REFERENCES ups_devices(id)");
    
    echo "Database updated successfully\n";
} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage() . "\n");
} catch (Exception $e) {
    die("Error: " . $e->getMessage() . "\n");
}