<?php

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

class ClientController
{
    private PDO $db;
    private Client $client;

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

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

        $clients = $this->client->readAll()->fetchAll(PDO::FETCH_ASSOC);

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

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

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

            if ($uploadResult['success']) {
                // CLAVE: El ID ya no se asigna manualmente. La DB se encarga.
                $this->client->name = $_POST['name'] ?? '';
                $this->client->logo = $uploadResult['path'];

                if ($this->client->create()) {
                    $_SESSION['message'] = "¡Cliente creado exitosamente!";
                    redirect('admin/clients');
                } else {
                    $error = "Falló al crear el cliente.";
                    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/clients/create.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Crear Nuevo Cliente");
    }

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

        if (!$this->client->readOne()) {
            $_SESSION['error'] = "Cliente no encontrado.";
            redirect('admin/clients');
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $currentLogo = $this->client->logo;
            
            // Lógica para manejar la eliminación del logo
            if (isset($_POST['delete_logo'])) {
                if ($currentLogo && file_exists(ROOT_PATH . '/public' . $currentLogo)) {
                    @unlink(ROOT_PATH . '/public' . $currentLogo);
                }
                $this->client->logo = null;
            }
            
            $uploadResult = $this->handleImageUpload('logo', $currentLogo);
            
            if ($uploadResult['success']) {
                $this->client->name = $_POST['name'] ?? '';
                if ($uploadResult['path'] !== null) {
                    $this->client->logo = $uploadResult['path'];
                }

                if ($this->client->update()) {
                    $_SESSION['message'] = "¡Cliente actualizado exitosamente!";
                    redirect('admin/clients');
                } else {
                    $error = "Falló al actualizar el cliente.";
                }
            } else {
                $error = $uploadResult['error'];
            }
        }

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

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

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

            if ($this->client->readOne()) {
                $logoToDelete = $this->client->logo;
                if ($this->client->delete()) {
                    if ($logoToDelete && file_exists(ROOT_PATH . '/public' . $logoToDelete)) {
                        @unlink(ROOT_PATH . '/public' . $logoToDelete);
                    }
                    $_SESSION['message'] = "¡Cliente eliminado exitosamente!";
                } else {
                    $_SESSION['error'] = "Falló al eliminar el cliente.";
                }
            } else {
                $_SESSION['error'] = "No se encontró el cliente a eliminar.";
            }
        }
        redirect('admin/clients');
    }

    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
        $uploadDir = ROOT_PATH . '/public/uploads/clients/';
        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', 'image/svg+xml'];
        if (!in_array($mimeType, $allowedMimeTypes)) {
            return ['success' => false, 'path' => null, 'error' => 'Formato de archivo no permitido (solo JPG, PNG, WEBP, SVG).'];
        }

        $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $newFileName = uniqid('client_', 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: Ruta estandarizada
        return ['success' => true, 'path' => '/uploads/clients/' . $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';
    }
}