<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/phpmailer.php';
require_once __DIR__ . '/../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;

class UserController {

    private $conn;

    public function __construct() {
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($this->conn->connect_error) {
            die("Error de conexión: " . $this->conn->connect_error);
        }
    }

    public function getUsers() {
        $result = $this->conn->query("SELECT * FROM users");
        $users = [];
        while ($row = $result->fetch_assoc()) {
            $users[] = $row;
        }
        return $users;
    }

    public function createUser($username, $password, $role, $email) {
        $hashed_password = password_hash($password, PASSWORD_BCRYPT);
        $stmt = $this->conn->prepare("INSERT INTO users (username, password, role, email) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssss", $username, $hashed_password, $role, $email);
        if ($stmt->execute()) {
            $this->sendWelcomeEmail($email, $username);
            return true;
        }
        return false;
    }

    private function sendWelcomeEmail($email, $username) {
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = SMTP_HOST;
            $mail->SMTPAuth = true;
            $mail->Username = SMTP_USER;
            $mail->Password = SMTP_PASS;
            $mail->SMTPSecure = SMTP_ENCRYPTION;
            $mail->Port = SMTP_PORT;
            $mail->setFrom(SMTP_USER, 'Glado');
            $mail->addAddress($email);
            $mail->Subject = 'Bienvenido a Glado';
            $mail->Body = "Hola $username,\n\nTu cuenta ha sido creada exitosamente.";
            $mail->send();
        } catch (Exception $e) {
            // No hacer nada si el correo falla
        }
    }

    public function updateUser($id, $username, $role) {
        $stmt = $this->conn->prepare("UPDATE users SET username = ?, role = ? WHERE id = ?");
        $stmt->bind_param("ssi", $username, $role, $id);
        return $stmt->execute();
    }

    public function deleteUser($id) {
        $stmt = $this->conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt->bind_param("i", $id);
        return $stmt->execute();
    }
}
?>