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

use PHPMailer\PHPMailer\PHPMailer;

class BranchController {

    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 getBranches() {
        $result = $this->conn->query("SELECT * FROM branches_config");
        $branches = [];
        while ($row = $result->fetch_assoc()) {
            $branches[] = $row;
        }
        return $branches;
    }

    public function createBranch($name, $db_host, $db_name, $db_user, $db_pass) {
        $stmt = $this->conn->prepare("INSERT INTO branches_config (name, db_host, db_name, db_user, db_pass) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("sssss", $name, $db_host, $db_name, $db_user, $db_pass);
        if ($stmt->execute()) {
            $this->sendNewBranchEmail($name);
            return true;
        }
        return false;
    }

    private function sendNewBranchEmail($branch_name) {
        $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($this->getAdminEmail()); // Asume que tenemos un método para obtener el email del admin
            $mail->Subject = 'Nueva Sucursal Creada';
            $mail->Body = "Se ha creado una nueva sucursal: $branch_name";
            $mail->send();
        } catch (Exception $e) {
            // No hacer nada si el correo falla
        }
    }

    private function getAdminEmail() {
        $result = $this->conn->query("SELECT email FROM users WHERE role = 'admin' LIMIT 1");
        return $result->fetch_assoc()['email'];
    }

    public function transferProducts($from_branch_id, $to_branch_id, $product_id, $quantity) {
        $from_branch = $this->getBranchConfig($from_branch_id);
        $to_branch = $this->getBranchConfig($to_branch_id);

        if ($from_branch && $to_branch) {
            $from_conn = new mysqli($from_branch['db_host'], $from_branch['db_user'], $from_branch['db_pass'], $from_branch['db_name']);
            $to_conn = new mysqli($to_branch['db_host'], $to_branch['db_user'], $to_branch['db_pass'], $to_branch['db_name']);

            if ($from_conn->connect_error || $to_conn->connect_error) {
                return false;
            }

            // Restar stock de la sucursal de origen
            $from_conn->query("UPDATE products SET stock = stock - $quantity WHERE id = $product_id");
            // Añadir stock a la sucursal de destino
            $to_conn->query("UPDATE products SET stock = stock + $quantity WHERE id = $product_id");

            $from_conn->close();
            $to_conn->close();

            return true;
        }
        return false;
    }

    private function getBranchConfig($branch_id) {
        $stmt = $this->conn->prepare("SELECT * FROM branches_config WHERE id = ?");
        $stmt->bind_param("i", $branch_id);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }
}
?>