<?php
require_once __DIR__ . '/config.php';

function cegic_current_user() {
    return $_SESSION['cegic_user'] ?? '';
}

function cegic_current_account() {
    global $CEGIC_ACCOUNTS;

    $user = cegic_current_user();

    if ($user === '' || !isset($CEGIC_ACCOUNTS[$user])) {
        return null;
    }

    return $CEGIC_ACCOUNTS[$user];
}

function cegic_public_posts() {
    $posts = cegic_posts();

    usort($posts, function($a, $b) {
        return strcmp($b['id'] ?? '', $a['id'] ?? '');
    });

    return $posts;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    cegic_json([
        'ok' => true,
        'posts' => cegic_public_posts()
    ]);
}

$user = cegic_current_user();
$account = cegic_current_account();

if ($user === '' || !$account) {
    cegic_json(['ok' => false, 'message' => 'No autorizado.'], 401);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $text = trim($_POST['text'] ?? '');

    if ($title === '' || $text === '') {
        cegic_json(['ok' => false, 'message' => 'Titulo y mensaje requeridos.'], 400);
    }

    $imageUrl = '';

    if (!empty($_FILES['image']['name']) && is_uploaded_file($_FILES['image']['tmp_name'])) {
        if (!is_dir(CEGIC_UPLOAD_DIR)) {
            mkdir(CEGIC_UPLOAD_DIR, 0755, true);
        }

        $extension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

        if (!in_array($extension, $allowed, true)) {
            cegic_json(['ok' => false, 'message' => 'Formato de imagen no permitido.'], 400);
        }

        $fileName = 'post-' . time() . '-' . mt_rand(1000, 9999) . '.' . $extension;
        $target = CEGIC_UPLOAD_DIR . '/' . $fileName;

        if (!move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
            cegic_json(['ok' => false, 'message' => 'No se pudo subir la imagen.'], 500);
        }

        $imageUrl = CEGIC_UPLOAD_URL . $fileName;
    }

    $posts = cegic_posts();

    $posts[] = [
        'id' => (string) time() . '-' . mt_rand(1000, 9999),
        'committeeKey' => $user,
        'committee' => $account['name'] ?? $user,
        'icon' => $account['icon'] ?? 'fa-newspaper',
        'title' => $title,
        'text' => $text,
        'image' => $imageUrl,
        'date' => date('d/m/Y H:i')
    ];

    cegic_save_posts($posts);

    cegic_json([
        'ok' => true,
        'posts' => cegic_public_posts()
    ]);
}

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $id = $_GET['id'] ?? '';

    if ($id === '') {
        cegic_json(['ok' => false, 'message' => 'ID requerido.'], 400);
    }

    $accountName = $account['name'] ?? '';
    $posts = cegic_posts();
    $nextPosts = [];
    $deleted = false;

    foreach ($posts as $post) {
        $postId = $post['id'] ?? '';
        $postUser = $post['committeeKey'] ?? '';
        $postCommittee = $post['committee'] ?? '';

        if ($postId === $id) {
            $canDelete = false;

            if ($postUser === $user) {
                $canDelete = true;
            }

            if ($postUser === '' && $postCommittee === $accountName) {
                $canDelete = true;
            }

            if ($postUser === '') {
                $canDelete = true;
            }

            if ($canDelete) {
                $deleted = true;
                continue;
            }

            cegic_json(['ok' => false, 'message' => 'No puede borrar esta publicacion.'], 403);
        }

        $nextPosts[] = $post;
    }

    cegic_save_posts($nextPosts);

    cegic_json([
        'ok' => true,
        'deleted' => $deleted,
        'posts' => cegic_public_posts()
    ]);
}

cegic_json(['ok' => false, 'message' => 'Metodo no permitido.'], 405);