<?php

namespace App\Controllers;

use App\Models\AreaGroupType;
use App\Models\Group;
use App\Services\AreaGroupTypeService;
use App\Services\GroupService;
use Exception;

class GroupController extends BaseController
{
    protected AreaGroupTypeService $areaGroupTypeService;
    protected GroupService $groupService;

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

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

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

    public function show($id)
    {
        $group = Group::find($id);
        $this->render('groups/show', ['group' => $group]);
    }

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

    public function edit($id)
    {
        $group = Group::find($id);
        $area = $this->groupService->getAreaByGroup($group);

        if (!$group) {
            $_SESSION['message'] = "Error: Grupo no encontrado.";
            $_SESSION['message_type'] = "danger";
            header("Location: " . BASE_HEADER . "areas/$area->id/show-groups");
            exit;
        }
        $this->render('groups/groups-edit', ['group' => $group, 'area' => $area]);
    }

    public function store()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $area_id = $_POST['area_id'] ?? null;
            $group_type_id = $_POST['group_type_id'] ?? null;
            $abbreviation = $_POST['abbreviation'] ?? null;
            $description = $_POST['group_name'] ?? null;
    
            if (empty($abbreviation) || empty($description)) {
                $_SESSION['message'] = "Error: Todos los campos son obligatorios.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "areas/$area_id/show-groups");
                exit;
            }

            $areaGroupType = $this->areaGroupTypeService->findByAreaAndGroupType($area_id, $group_type_id);
            if (!$areaGroupType) {
                $_SESSION['message'] = "Error: Datos erróneos.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "areas/$area_id/show-groups");
                exit;
            }
    
            try {
                $group = new Group();
                $group->area_group_type_id = $areaGroupType->id;
                $group->abbreviation = htmlspecialchars($abbreviation);
                $group->description = htmlspecialchars($description);
                $group->save();

                $_SESSION['message'] = "¡Grupo creado exitosamente!";
                $_SESSION['message_type'] = "success";
                header("Location: " . BASE_HEADER . "areas/$area_id/show-groups");
                exit;
            } catch (Exception $e) {
                $_SESSION['message'] = "Error al guardar: " . $e->getMessage();
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "areas/$area_id/show-groups");
                exit;
            }

        }
    }

    public function update($id)
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' 
            && isset($_POST['_method']) 
            && $_POST['_method'] === 'PUT') 
        {
            try {
                $group = Group::find($id);

                if (!$group) {
                    $_SESSION['message'] = "Error: Grupo no encontrado.";
                    $_SESSION['message_type'] = "danger";
                    header("Location: " . BASE_HEADER . "areas");
                    exit;
                }

                $area = $this->groupService->getAreaByGroup($group);

                $group->abbreviation = trim($_POST['abbreviation'] ?? '');
                $group->description  = trim($_POST['description'] ?? '');
                $group->active       = isset($_POST['active']) ? 1 : 0;

                if (empty($group->abbreviation) || empty($group->description)) {
                    $_SESSION['message'] = "Error: Todos los campos son obligatorios.";
                    $_SESSION['message_type'] = "danger";
                    header("Location: " . BASE_HEADER . "groups/$id/edit");
                    exit;
                }

                $group->save();

                $_SESSION['message'] = "¡Grupo actualizado exitosamente!";
                $_SESSION['message_type'] = "success";
                header("Location: " . BASE_HEADER . "areas/$area->id/show-groups");
                exit;

            } catch (Exception $e) {
                $_SESSION['message'] = "Error al actualizar: " . $e->getMessage();
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "groups/$id/edit");
                exit;
            }
        }

        die("Error: Método no permitido.");
    }

    public function delete($id)
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['_method']) && $_POST['_method'] === 'DELETE') {
            $group = Group::find($id);
            $area = $this->groupService->getAreaByGroup($group);
            
            if (!$group) {
                $_SESSION['message'] = "Error: No se pudo eliminar el grupo.";
                $_SESSION['message_type'] = "danger";
            }else if ($this->groupService->hasSubgroups($group->id)) {
                $_SESSION['message'] = "No se puede eliminar este grupo porque tiene subgrupos asociados.";
                $_SESSION['message_type'] = "danger";
            } else {
                $group->delete($group->id);
                $_SESSION['message'] = "¡Grupo eliminado exitosamente!";
                $_SESSION['message_type'] = "success";
            }

            header("Location: " . BASE_HEADER . "areas/$area->id/show-groups");
            exit;
        }
        die("Error: Método no permitido.");
    }
}
