<?php

require_once dirname(__DIR__) . "/domain/User.php";
require_once dirname(__DIR__) . "/domain/Wall.php";
require_once dirname(__DIR__) . "/services/WallRepositoryService.php";
require_once dirname(__DIR__) . "/services/InboxRepositoryService.php";
$patron = "/^[[:digit:]]+\$/";
if (preg_match($patron, $_GET['usuario'])) {
    $idUsuario = $_GET['usuario'];
} else {
    header('location:index.php?error=4');
    exit;
}
$wallRepo = new WallRepositoryService();
$inboxRepo = new InboxRepositoryService();
$wallResult = $wallRepo->getWallByUserId($idUsuario);
//
$MessageLimitResult = $inboxRepo->getMessageLimit($idUsuario);
//
$MessageNumResult = $inboxRepo->getMessageNum($idUsuario);
//
if ($wallResult->num_rows > 0) {
    $userHasWall = true;
} else {
    $userHasWall = false;
}
if ($userHasWall) {
    $objWall = $wallResult->fetch_object();
    $privacidad = $objWall->privacidad;
    $idMuro = $objWall->id_muro;
    $anonimoLectura = $objWall->flag_anonimo_lectura;
$mysession->initSession();
$content = $_POST["content"];
$toWall = $_POST["toWall"];
$patron = "/^[[:digit:]]+\$/";
if (isset($_SESSION['id']) and preg_match($patron, $_SESSION['id'])) {
    $fromUser = $_SESSION['id'];
} else {
    //El id 1 pertenece al usuario anonimo
    $fromUser = 1;
}
if (isset($_POST["toUser"]) and preg_match($patron, $_POST["toUser"])) {
    $toUser = $_POST["toUser"];
} else {
    header('location:index.php?error=4');
    exit;
}
echo "string";
$wallRepo = new WallRepositoryService();
$wallResult = $wallRepo->getWallByUserId($toUser);
if ($row = $wallResult->fetch_object()) {
    $wall = new Wall();
    $messages = $wall->getMessages($row->limite_muro, $toUser);
    if (count($messages) < $row->limite_muro) {
        $cbcCipher = new CbcCipher($content);
        $content = $cbcCipher->encrypt();
        $message = new Message($content, $toWall, $fromUser);
        header('location: ../../index.php?usuario=' . $toUser);
    } else {
        header('location: ../../index.php?usuario=' . $toUser . '&alert');
    }
}