<?php

namespace App\Controllers;

use App\Models\AreaGroupType;
use App\Models\GroupType;
use App\Services\AreaGroupTypeService;

class GroupTypeController extends BaseController
{
    protected AreaGroupTypeService $areaGroupTypeService;

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

        $this->areaGroupTypeService = new AreaGroupTypeService();
    }

    public function index()
    {
        $grouptypes = GroupType::getActives();
        $this->render('grouptypes/grouptypes-index', ['grouptypes' => $grouptypes]);
    }

    public function show($id)
    {
        $grouptype = GroupType::find($id);
        $this->render('grouptypes/show', ['grouptype' => $grouptype]);
    }

    public function create()
    {
        $this->render('grouptypes/grouptypes-create'); 
    }

    public function edit($id)
    {
        $grouptype = GroupType::find($id);
        if (!$grouptype) {
            $_SESSION['message'] = "Error: Tipo de grupo no encontrado.";
            $_SESSION['message_type'] = "danger";
            header("Location: " . BASE_HEADER . "grouptypes");
            exit;
        }
        $this->render('grouptypes/grouptypes-edit', ['grouptype' => $grouptype]);
    }

    public function store()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $abbreviation = $_POST['abbreviation'] ?? '';
            $description = $_POST['description'] ?? '';
    
            if (empty($abbreviation) || empty($description)) {
                $_SESSION['message'] = "Error: Todos los campos son obligatorios.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "grouptypes/create");
                exit;
            }
    
            $grouptype = new GroupType();
            $grouptype->abbreviation = $abbreviation;
            $grouptype->description = $description;
            $grouptype->save();
    
            $_SESSION['message'] = "¡Tipo de grupo creado exitosamente!";
            $_SESSION['message_type'] = "success";
            header("Location: " . BASE_HEADER . "grouptypes");
            exit;
        }
    }

    public function update($id) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['_method']) && $_POST['_method'] === 'PUT') {
            $grouptype = GroupType::find($id);
    
            if (!$grouptype) {
                $_SESSION['message'] = "Error: Tipo de grupo no encontrado.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "grouptypes");
                exit;
            }
    
            $grouptype->abbreviation = $_POST['abbreviation'] ?? '';
            $grouptype->description = $_POST['description'] ?? '';
            $grouptype->active = $_POST['active'] ?? 0;
    
            if (empty($grouptype->abbreviation) || empty($grouptype->description)) {
                $_SESSION['message'] = "Error: Todos los campos son obligatorios.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "grouptypes/$id/edit");
                exit;
            }
    
            $grouptype->save();
            $_SESSION['message'] = "¡Tipo de grupo actualizado exitosamente!";
            $_SESSION['message_type'] = "success";
    
            header("Location: " . BASE_HEADER . "grouptypes");
            exit;
        }
        die("Error: Método no permitido.");
    }
    

    public function delete($id)
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['_method']) && $_POST['_method'] === 'DELETE') {
            $grouptype = GroupType::find($id);
            
            if (!$grouptype) {
                $_SESSION['message'] = "Error: No se pudo eliminar el tipo de grupo.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "grouptypes");
                exit;
            }

            $grouptype->delete($grouptype->id);
            $_SESSION['message'] = "¡Tipo de grupo eliminado exitosamente!";
            $_SESSION['message_type'] = "success";
            header("Location: " . BASE_HEADER . "grouptypes");
            exit;
        }
        die("Error: Método no permitido.");
    }

    public function assignGroupType()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $area_id = $_POST['area_id'] ?? null;
            $group_type_id = $_POST['group_type_id'] ?? null;

            if (!$area_id || !$group_type_id) {
                $_SESSION['message'] = "Error: Datos inválidos.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . $_SERVER['HTTP_REFERER']);
                exit;
            }

            if ($this->areaGroupTypeService->exists($area_id, $group_type_id)) {
                $_SESSION['message'] = "Este tipo de grupo ya está asociado a esta área.";
                $_SESSION['message_type'] = "danger";
            } else {
                $this->areaGroupTypeService->assign($area_id, $group_type_id);
                $_SESSION['message'] = "¡Tipo de grupo asociado exitosamente!";
                $_SESSION['message_type'] = "success";
            }

            header("Location: " . $_SERVER['HTTP_REFERER']);
            exit;
        }
    }

    public function unassignGroupType()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $area_id = $_POST['area_id'] ?? null;
            $group_type_id = $_POST['group_type_id'] ?? null;

            if (!$area_id || !$group_type_id) {
                $_SESSION['message'] = "Error: Datos inválidos.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . $_SERVER['HTTP_REFERER']);
                exit;
            }

            $areaGroupType = $this->areaGroupTypeService->findByAreaAndGroupType($area_id, $group_type_id);

            if (!$areaGroupType) {
                $_SESSION['message'] = "El tipo de grupo no está asociado al área.";
                $_SESSION['message_type'] = "danger";
            } elseif ($this->areaGroupTypeService->hasGroups($areaGroupType->id)) {
                $_SESSION['message'] = "No se puede eliminar este tipo de grupo porque tiene grupos asociados.";
                $_SESSION['message_type'] = "danger";
            } else {
                $areaGroupType->delete($areaGroupType->id);
                $_SESSION['message'] = "¡Tipo de grupo eliminado exitosamente!";
                $_SESSION['message_type'] = "success";
            }

            header("Location: " . $_SERVER['HTTP_REFERER']);
            exit;
        }
    }

}
