<?php

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

class TechStackController
{
    private PDO $db;
    private TechStack $tech;

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

    public function index(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }
        $techStackItems = $this->tech->readAll()->fetchAll(PDO::FETCH_ASSOC);
        ob_start();
        require_once ROOT_PATH . '/app/views/admin/tech_stack/index.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Gestionar Tech Stack");
    }

    public function create(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }
        $error = null;
        $techData = [];

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

            if ($uploadResult['success']) {
                $this->tech->name = $_POST['name'] ?? '';
                $this->tech->type = $_POST['type'] ?? '';
                $this->tech->logo = $uploadResult['path'];

                if ($this->tech->create()) {
                    $_SESSION['message'] = "¡Tecnología añadida exitosamente!";
                    redirect('admin/tech_stack');
                } else {
                    $error = "Falló al añadir la tecnología.";
                    if ($uploadResult['path']) { @unlink(ROOT_PATH . '/public' . $uploadResult['path']); }
                }
            } else {
                $error = $uploadResult['error'];
            }
        }

        ob_start();
        require_once ROOT_PATH . '/app/views/admin/tech_stack/create.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Añadir Tecnología");
    }

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

        if (!$this->tech->readOne()) {
            $_SESSION['error'] = "Tecnología no encontrada.";
            redirect('admin/tech_stack');
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $currentLogo = $this->tech->logo;
            if (isset($_POST['delete_logo'])) {
                if ($currentLogo && file_exists(ROOT_PATH . '/public' . $currentLogo)) {
                    @unlink(ROOT_PATH . '/public' . $currentLogo);
                }
                $this->tech->logo = null;
            }
            
            $uploadResult = $this->handleImageUpload('logo', $currentLogo);
            
            if ($uploadResult['success']) {
                $this->tech->id = $_POST['id'];
                $this->tech->name = $_POST['name'] ?? '';
                $this->tech->type = $_POST['type'] ?? '';
                if ($uploadResult['path'] !== null) {
                    $this->tech->logo = $uploadResult['path'];
                }

                if ($this->tech->update()) {
                    $_SESSION['message'] = "¡Tecnología actualizada exitosamente!";
                    redirect('admin/tech_stack');
                } else {
                    $error = "Falló al actualizar la tecnología.";
                }
            } else {
                $error = $uploadResult['error'];
            }
        }

        ob_start();
        require_once ROOT_PATH . '/app/views/admin/tech_stack/edit.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Editar Tecnología");
    }

    public function delete(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->tech->id = $_POST['id'] ?? 0;
            if ($this->tech->readOne()) {
                $logoToDelete = $this->tech->logo;
                if ($this->tech->delete()) {
                    if ($logoToDelete && file_exists(ROOT_PATH . '/public' . $logoToDelete)) {
                        @unlink(ROOT_PATH . '/public' . $logoToDelete);
                    }
                    $_SESSION['message'] = "¡Tecnología eliminada exitosamente!";
                } else {
                    $_SESSION['error'] = "Falló al eliminar la tecnología.";
                }
            }
        }
        redirect('admin/tech_stack');
    }

    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.'];
        }

        $uploadDir = ROOT_PATH . '/public/uploads/tech_stack/';
        if (!is_dir($uploadDir)) { mkdir($uploadDir, 0775, true); }

        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($file['tmp_name']);
        $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/svg+xml'];
        if (!in_array($mimeType, $allowedMimeTypes)) {
            return ['success' => false, 'path' => null, 'error' => 'Formato no permitido (JPG, PNG, WebP, SVG).'];
        }
        
        $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if ($mimeType === 'image/svg+xml' && $fileExtension === '') { $fileExtension = 'svg'; }
        $newFileName = uniqid('tech_', true) . '.' . $fileExtension;
        
        if (move_uploaded_file($file['tmp_name'], $uploadDir . $newFileName)) {
            if ($oldImagePath && file_exists(ROOT_PATH . '/public' . $oldImagePath)) {
                @unlink(ROOT_PATH . '/public' . $oldImagePath);
            }
            return ['success' => true, 'path' => '/uploads/tech_stack/' . $newFileName, 'error' => null];
        }
        return ['success' => false, 'path' => null, 'error' => 'No se pudo mover el archivo subido.'];
    }

    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';
    }
}