<?php
// --- Dependencias ---
require_once __DIR__ . '/vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Twilio\Rest\Client;

// --- Funciones de Prueba ---

function testDbConnection($host, $user, $pass, $name) {
    $conn = @new mysqli($host, $user, $pass);
    if ($conn->connect_error) {
        return ["success" => false, "message" => "Error de conexión a MySQL: " . $conn->connect_error];
    }
    $sql = "CREATE DATABASE IF NOT EXISTS `$name` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
    if (!$conn->query($sql)) {
        $error = $conn->error;
        $conn->close();
        return ["success" => false, "message" => "Error al crear la base de datos: " . $error];
    }
    $conn->close();
    return ["success" => true, "message" => "Conexión a la Base de Datos exitosa."];
}

function testSmtp($host, $port, $user, $pass, $encryption, $admin_email) {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = $host;
        $mail->SMTPAuth = true;
        $mail->Username = $user;
        $mail->Password = $pass;
        $mail->SMTPSecure = $encryption;
        $mail->Port = $port;
        $mail->setFrom($user, 'Instalador Glado');
        $mail->addAddress($admin_email);
        $mail->isHTML(true);
        $mail->Subject = 'Prueba de Correo SMTP - Glado';
        $mail->Body = '¡La configuración SMTP funciona correctamente!';
        $mail->send();
        return ["success" => true, "message" => "Correo de prueba enviado exitosamente a " . htmlspecialchars($admin_email)];
    } catch (Exception $e) {
        return ["success" => false, "message" => "Error de PHPMailer: {$mail->ErrorInfo}"];
    }
}

function testTwilio($sid, $token, $from, $to) {
    try {
        $client = new Client($sid, $token);
        $client->messages->create("whatsapp:" . $to, ['from' => "whatsapp:" . $from, 'body' => '¡Hola desde Glado! La configuración de Twilio funciona.']);
        return ["success" => true, "message" => "Mensaje de prueba enviado exitosamente a " . htmlspecialchars($to)];
    } catch (\Twilio\Exceptions\TwilioException $e) {
        return ["success" => false, "message" => "Error de Twilio: " . $e->getMessage()];
    }
}

// --- Lógica Principal ---

$action = $_GET['action'] ?? '';

// Modo de Prueba Individual
if (strpos($action, 'test_') === 0) {
    header('Content-Type: application/json');
    $test_type = substr($action, 5);
    $response = ["success" => false, "message" => "Prueba no reconocida."];

    if ($test_type === 'db') {
        $response = testDbConnection($_GET['db_host'], $_GET['db_user'], $_GET['db_pass'], $_GET['db_name']);
    } elseif ($test_type === 'smtp') {
        $response = testSmtp($_GET['smtp_host'], $_GET['smtp_port'], $_GET['smtp_user'], $_GET['smtp_pass'], $_GET['smtp_encryption'], $_GET['admin_email']);
    } elseif ($test_type === 'twilio') {
        $response = testTwilio($_GET['twilio_sid'], $_GET['twilio_token'], $_GET['twilio_whatsapp_from'], $_GET['admin_phone']);
    }
    echo json_encode($response);
    exit();
}

// Modo de Instalación Completa
if ($action === 'install') {
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('X-Accel-Buffering: no');

    function sendMessage($message, $progress) {
        $data = ['message' => $message, 'progress' => $progress];
        echo "id: " . time() . PHP_EOL;
        echo "data: " . json_encode($data) . PHP_EOL;
        echo PHP_EOL;
        ob_flush();
        flush();
    }

    function sendFinalResponse($status, $message) {
        $data = ['status' => $status, 'message' => $message];
        echo "id: " . time() . PHP_EOL;
        echo "data: " . json_encode($data) . PHP_EOL;
        echo PHP_EOL;
        ob_flush();
        flush();
    }
    
    $params = $_GET;

    sendMessage("Iniciando instalación final...", 10);
    sleep(1);

    $db_host = $params['db_host'];
    $db_user = $params['db_user'];
    $db_pass = $params['db_pass'];
    $db_name = $params['db_name'];
    $conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

    sendMessage("Creando tablas...", 20);
    $sql_queries = [
        "CREATE TABLE `users` (`id` INT AUTO_INCREMENT PRIMARY KEY, `username` VARCHAR(50) NOT NULL UNIQUE, `password` VARCHAR(255) NOT NULL, `role` ENUM('admin', 'vendedor') NOT NULL, `email` VARCHAR(100))",
        "CREATE TABLE `branches` (`id` INT AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(100) NOT NULL)",
        "CREATE TABLE `categories` (`id` INT AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(100) NOT NULL)",
        "CREATE TABLE `products` (`id` INT AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(100) NOT NULL, `price` DECIMAL(10, 2) NOT NULL, `stock` INT NOT NULL, `category_id` INT, FOREIGN KEY (`category_id`) REFERENCES `categories`(`id`))",
        "CREATE TABLE `sales` (`id` INT AUTO_INCREMENT PRIMARY KEY, `user_id` INT, `total` DECIMAL(10, 2) NOT NULL, `payment_method` ENUM('efectivo', 'transferencia', 'tarjeta'), `notes` TEXT, `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`))",
        "CREATE TABLE `sale_items` (`id` INT AUTO_INCREMENT PRIMARY KEY, `sale_id` INT, `product_id` INT, `quantity` INT, FOREIGN KEY (`sale_id`) REFERENCES `sales`(`id`), FOREIGN KEY (`product_id`) REFERENCES `products`(`id`))",
        "CREATE TABLE `customers` (`id` INT AUTO_INCREMENT PRIMARY KEY, `phone` VARCHAR(20) NOT NULL UNIQUE, `points` INT DEFAULT 0, `last_purchase_date` DATE, `referral_code` VARCHAR(10) UNIQUE)",
        "CREATE TABLE `referrals` (`id` INT AUTO_INCREMENT PRIMARY KEY, `referrer_id` INT, `referred_id` INT, `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (`referrer_id`) REFERENCES `customers`(`id`), FOREIGN KEY (`referred_id`) REFERENCES `customers`(`id`))",
        "CREATE TABLE `points_log` (`id` INT AUTO_INCREMENT PRIMARY KEY, `customer_id` INT, `points` INT, `reason` VARCHAR(255), `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (`customer_id`) REFERENCES `customers`(`id`))",
        "CREATE TABLE `promotions` (`id` INT AUTO_INCREMENT PRIMARY KEY, `code` VARCHAR(50) NOT NULL UNIQUE, `type` ENUM('discount', 'buy_x_get_y') NOT NULL, `value` DECIMAL(10, 2) NOT NULL, `uses_limit` INT, `uses_count` INT DEFAULT 0)",
        "CREATE TABLE `gifts` (`id` INT AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(100) NOT NULL, `points_cost` INT, `birthday_gift` BOOLEAN DEFAULT FALSE)",
        "CREATE TABLE `notifications_log` (`id` INT AUTO_INCREMENT PRIMARY KEY, `customer_id` INT, `message` TEXT, `status` VARCHAR(50), `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (`customer_id`) REFERENCES `customers`(`id`))",
        "CREATE TABLE `cash_closures` (`id` INT AUTO_INCREMENT PRIMARY KEY, `user_id` INT, `total_efectivo` DECIMAL(10, 2), `total_transferencia` DECIMAL(10, 2), `total_tarjeta` DECIMAL(10, 2), `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`))",
        "CREATE TABLE `tasks` (`id` INT AUTO_INCREMENT PRIMARY KEY, `description` TEXT, `completed` BOOLEAN DEFAULT FALSE, `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP)",
        "CREATE TABLE `suppliers` (`id` INT AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(100) NOT NULL, `contact_person` VARCHAR(100), `phone` VARCHAR(20), `email` VARCHAR(100))",
        "CREATE TABLE `branches_config` (`id` INT AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(100) NOT NULL, `db_host` VARCHAR(255), `db_name` VARCHAR(255), `db_user` VARCHAR(255), `db_pass` VARCHAR(255))"
    ];
    foreach ($sql_queries as $sql) { $conn->query($sql); }
    sleep(1);

    sendMessage("Insertando datos de ejemplo...", 50);
    $sql_inserts = [
        "INSERT INTO `categories` (`name`) VALUES ('Helados Paleta'), ('Helados Cremosos'), ('Bebidas'), ('Snacks')",
        "INSERT INTO `products` (`name`, `price`, `stock`, `category_id`) VALUES ('Paleta de Fresa', 10.00, 100, 1), ('Paleta de Chocolate', 10.00, 100, 1), ('Helado de Vainilla', 15.00, 50, 2), ('Agua Pura', 5.00, 200, 3), ('Papitas', 8.00, 150, 4)",
    ];
    foreach ($sql_inserts as $sql) { $conn->query($sql); }
    sleep(1);

    sendMessage("Creando usuario administrador...", 70);
    $hashed_password = password_hash($params['admin_pass'], PASSWORD_BCRYPT);
    $stmt = $conn->prepare("INSERT INTO `users` (`username`, `password`, `role`, `email`) VALUES (?, ?, 'admin', ?)");
    $stmt->bind_param("sss", $params['admin_user'], $hashed_password, $params['admin_email']);
    $stmt->execute();
    $stmt = $conn->prepare("INSERT INTO `branches` (`name`) VALUES (?)");
    $stmt->bind_param("s", $params['branch_name']);
    $stmt->execute();
    $conn->close();
    sleep(1);

    sendMessage("Guardando archivos de configuración...", 90);
    file_put_contents('config/database.php', "<?php\ndefine('DB_HOST', '{$params['db_host']}');\ndefine('DB_NAME', '{$params['db_name']}');\ndefine('DB_USER', '{$params['db_user']}');\ndefine('DB_PASS', '{$params['db_pass']}');");
    file_put_contents('config/phpmailer.php', "<?php\ndefine('SMTP_HOST', '{$params['smtp_host']}');\ndefine('SMTP_PORT', {$params['smtp_port']});\ndefine('SMTP_USER', '{$params['smtp_user']}');\ndefine('SMTP_PASS', '{$params['smtp_pass']}');\ndefine('SMTP_ENCRYPTION', '{$params['smtp_encryption']}');");
    file_put_contents('config/whatsapp.php', "<?php\ndefine('TWILIO_SID', '{$params['twilio_sid']}');\ndefine('TWILIO_TOKEN', '{$params['twilio_token']}');\ndefine('TWILIO_WHATSAPP_FROM', '{$params['twilio_whatsapp_from']}');");
    sleep(1);

    $success_message = '<div class="alert alert-success"><h3>¡Instalación completada con éxito!</h3><p>La aplicación está lista para usarse. Por favor, por seguridad, <strong>elimina el archivo install.php</strong>.</p><a href="views/auth/login.php" class="btn btn-primary mt-2">Ir al Login</a></div>';
    sendFinalResponse('success', $success_message);
}
