<?php

require_once ROOT_PATH . '/app/models/TeamMember.php';

/**
 * Class TeamMemberController
 *
 * Gestiona la lógica CRUD para los miembros del equipo, incluyendo la subida de avatares.
 */
class TeamMemberController
{
    private PDO $db;
    private TeamMember $teamMember;

    public function __construct(PDO $db)
    {
        $this->db = $db;
        $this->teamMember = new TeamMember($this->db);
    }

    public function index(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }

        $teamMembers = $this->teamMember->readAll()->fetchAll(PDO::FETCH_ASSOC);

        ob_start();
        require_once ROOT_PATH . '/app/views/admin/team_members/index.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Gestionar Equipo");
    }

    public function create(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }
        
        $error = null;
        $memberData = []; // Para repoblar el formulario en caso de error

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $memberData = $_POST;
            $uploadResult = $this->handleImageUpload('avatar');

            if ($uploadResult['success']) {
                $this->teamMember->name = $_POST['name'] ?? '';
                $this->teamMember->role = $_POST['role'] ?? '';
                $this->teamMember->bio = $_POST['bio'] ?? '';
                $this->teamMember->social = $_POST['social'] ?? '{}';
                $this->teamMember->avatar = $uploadResult['path'];

                if ($this->teamMember->create()) {
                    $_SESSION['message'] = "¡Miembro del equipo creado exitosamente!";
                    redirect('admin/team_members');
                } else {
                    $error = "Falló al crear el miembro del equipo.";
                    if ($uploadResult['path'] && file_exists(ROOT_PATH . '/public' . $uploadResult['path'])) {
                        @unlink(ROOT_PATH . '/public' . $uploadResult['path']);
                    }
                }
            } else {
                $error = $uploadResult['error'];
            }
        }

        ob_start();
        require_once ROOT_PATH . '/app/views/admin/team_members/create.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Añadir Miembro del Equipo");
    }

    public function edit(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }
        
        $error = null;
        $this->teamMember->id = $_GET['id'] ?? 0;

        if (!$this->teamMember->readOne()) {
            $_SESSION['error'] = "Miembro del equipo no encontrado.";
            redirect('admin/team_members');
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $currentAvatar = $this->teamMember->avatar;

            // Lógica para manejar la eliminación del avatar
            if (isset($_POST['delete_avatar'])) {
                if ($currentAvatar && file_exists(ROOT_PATH . '/public' . $currentAvatar)) {
                    @unlink(ROOT_PATH . '/public' . $currentAvatar);
                }
                $this->teamMember->avatar = null;
            }

            $uploadResult = $this->handleImageUpload('avatar', $currentAvatar);
            
            if ($uploadResult['success']) {
                $this->teamMember->name = $_POST['name'] ?? '';
                $this->teamMember->role = $_POST['role'] ?? '';
                $this->teamMember->bio = $_POST['bio'] ?? '';
                $this->teamMember->social = $_POST['social'] ?? '{}';

                if ($uploadResult['path'] !== null) {
                    $this->teamMember->avatar = $uploadResult['path'];
                }

                if ($this->teamMember->update()) {
                    $_SESSION['message'] = "¡Miembro del equipo actualizado exitosamente!";
                    redirect('admin/team_members');
                } else {
                    $error = "Falló al actualizar el miembro del equipo.";
                }
            } else {
                $error = $uploadResult['error'];
            }
        }

        ob_start();
        require_once ROOT_PATH . '/app/views/admin/team_members/edit.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Editar Miembro del Equipo");
    }

    public function delete(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->teamMember->id = $_POST['id'] ?? 0;

            if ($this->teamMember->readOne()) {
                $avatarToDelete = $this->teamMember->avatar;
                if ($this->teamMember->delete()) {
                    if ($avatarToDelete && file_exists(ROOT_PATH . '/public' . $avatarToDelete)) {
                        @unlink(ROOT_PATH . '/public' . $avatarToDelete);
                    }
                    $_SESSION['message'] = "¡Miembro del equipo eliminado exitosamente!";
                } else {
                    $_SESSION['error'] = "Falló al eliminar el miembro del equipo.";
                }
            } else {
                $_SESSION['error'] = "No se encontró el miembro a eliminar.";
            }
        }
        redirect('admin/team_members');
    }

    private function handleImageUpload(string $fileInputName, ?string $oldImagePath = null): array
    {
        if (!isset($_FILES[$fileInputName]) || $_FILES[$fileInputName]['error'] === UPLOAD_ERR_NO_FILE) {
            return ['success' => true, 'path' => null, 'error' => null];
        }

        $file = $_FILES[$fileInputName];
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return ['success' => false, 'path' => null, 'error' => 'Error al subir el archivo.'];
        }

        // CLAVE: Ruta estandarizada para todos los archivos subidos
        $uploadDir = ROOT_PATH . '/public/uploads/team_members/';
        if (!is_dir($uploadDir)) {
            if (!mkdir($uploadDir, 0775, true)) {
                return ['success' => false, 'path' => null, 'error' => 'Error: No se pudo crear el directorio de subida.'];
            }
        }

        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($file['tmp_name']);
        $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (!in_array($mimeType, $allowedMimeTypes)) {
            return ['success' => false, 'path' => null, 'error' => 'Formato de archivo no permitido (solo JPG, PNG o WebP).'];
        }

        $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $newFileName = uniqid('team_', true) . '.' . $fileExtension;
        $destPath = $uploadDir . $newFileName;

        if (!move_uploaded_file($file['tmp_name'], $destPath)) {
            return ['success' => false, 'path' => null, 'error' => 'No se pudo mover el archivo subido.'];
        }

        if ($oldImagePath && file_exists(ROOT_PATH . '/public' . $oldImagePath)) {
            @unlink(ROOT_PATH . '/public' . $oldImagePath);
        }

        // CLAVE: Devolver la ruta estandarizada
        return ['success' => true, 'path' => '/uploads/team_members/' . $newFileName, 'error' => null];
    }

    private function renderAdminLayout(string $content, string $pageTitle): void
    {
        ob_start();
        echo $content;
        $content = ob_get_clean();
        require_once ROOT_PATH . '/app/views/admin/layout.php';
    }
}