<?php

namespace App\Controllers;

use App\Helpers\DateHelper;
use App\Models\Response;
use App\Services\ResponseService;
use App\Services\UserService;

class InboxController extends BaseController
{

    protected ResponseService $responseService;

    public function __construct() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $this->responseService = new ResponseService();
    }

    public function index()
    {
        $user = UserService::getUser();
        if (!$user) {
            $_SESSION['message'] = "Acceso denegado.";
            $_SESSION['message_type'] = "danger";
            header("Location: " . BASE_HEADER);
            exit;
        }

        $responses = $this->responseService->getResponsesForUser($user->id);

        $this->render('inbox/inbox-index', ['responses' => $responses]);
    }

    public function show($id)
    {
        $response = Response::find($id);

        if (!$response) {
            $_SESSION['message'] = "Mensaje no encontrado.";
            $_SESSION['message_type'] = "danger";
            header("Location: " . BASE_HEADER . "inbox");
            exit;
        }

        if (!$response->is_read) {
            $this->responseService->markResponseAsRead($id);
        }

        $process = $response->process();
        $responsible = $response->user();
        $user = $process->user();
        $formatedDate = DateHelper::traducirFecha($response->created_at);

        $this->render('inbox/inbox-show', ['response' => $response, 'process' => $process, 'user' => $user, 'responsible' => $responsible, 'formatedDate' => $formatedDate]);
    }

    public function registerDownload()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents("php://input"), true);
            $responseId = $data['response_id'] ?? null;

            if (!$responseId) {
                echo json_encode(['status' => 'error', 'message' => 'ID de respuesta no proporcionado']);
                return;
            }

            $response = Response::find($responseId);
            if (!$response) {
                echo json_encode(['status' => 'error', 'message' => 'Respuesta no encontrada']);
                return;
            }

            if (empty($response->downloaded_at)) {
                $response->downloaded_at = date('Y-m-d H:i:s');
                $response->save();
            }

            echo json_encode(['status' => 'success']);
        }
    }

}