<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Fractional;
use App\Models\FormTemplate;
use App\Models\Image;
use App\Models\Section;

class FractionalController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Si quieres mostrar el proyecto desde la section:
        // $fractionals = Fractional::with(['section.project'])->get();
        $fractionals = Fractional::with(['section.project', 'image'])->latest()->get();
    return view('fractionals.index', compact('fractionals'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function store(Request $request)
{
    $request->validate([
        'section_id'       => 'required|exists:sections,id',
        'name'             => 'required|string|max:255',
        'svg_data'         => ['nullable','string'],
        'form_template_id' => 'nullable|exists:form_templates,id',
        'status'           => 'required|string|in:available,reserved,sold',
        'image_id'         => 'nullable|exists:images,id',
    ]);

    // 1) Tomar el proyecto de la sección
    $section = Section::findOrFail($request->section_id);
    if (empty($section->project_id)) {
        return back()->withErrors([
            'section_id' => 'La sección seleccionada no está ligada a ningún proyecto.'
        ])->withInput();
    }

    // 2) Preparar datos a insertar
    $data = $request->only(['section_id','name','form_template_id','image_id','status']);
    $data['project_id'] = $section->project_id; // 👈 clave
    $data['svg_data']   = $this->normalizePoints($request->input('svg_data'));

    // 3) Crear
    Fractional::create($data);

    return redirect()->route('fractionals.index')
        ->with('success', 'Fractional creado correctamente.');
}

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $fractional = Fractional::with(['section.project'])->findOrFail($id);
        return view('fractionals.show', compact('fractional'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        $images     = Image::all();
        $fractional = Fractional::with(['section.project','image'])->findOrFail($id);
        $sections   = Section::with('project')->get();
        $templates  = FormTemplate::all();

        // Imagen base: primero Section->image (string path), luego Project->image->path, luego company_logo
        $backgroundImage = null;
        $sec = $fractional->section;

        if ($sec && !empty($sec->image)) {
            $backgroundImage = asset('storage/' . ltrim($sec->image, '/'));
        } elseif ($sec && $sec->project && $sec->project->image && !empty($sec->project->image->path)) {
            $backgroundImage = asset('storage/' . ltrim($sec->project->image->path, '/'));
        } elseif ($sec && $sec->project && !empty($sec->project->company_logo)) {
            $backgroundImage = asset('storage/' . ltrim($sec->project->company_logo, '/'));
        }

        return view('fractionals.edit', compact(
            'images','fractional','sections','templates','backgroundImage'
        ));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Fractional $fractional)
        {
            $clean = $this->normalizePoints($request->input('svg_data'));

            // Si cambian la sección, actualiza también el proyecto
            if ($request->filled('section_id') && (int)$request->section_id !== (int)$fractional->section_id) {
                $sec = Section::findOrFail($request->section_id);
                if (empty($sec->project_id)) {
                    return back()->withErrors([
                        'section_id' => 'La sección seleccionada no está ligada a ningún proyecto.'
                    ])->withInput();
                }
                $fractional->section_id = $sec->id;
                $fractional->project_id = $sec->project_id;
            }

            // Otros campos
            if ($request->filled('name'))             $fractional->name = $request->name;
            if ($request->has('form_template_id'))    $fractional->form_template_id = $request->form_template_id ?: null;
            if ($request->has('image_id'))            $fractional->image_id = $request->image_id ?: null;
            if ($request->filled('status'))           $fractional->status = $request->status;
            $fractional->svg_data = $clean;

            $fractional->save();

            return back()->with('success', 'Fractional actualizado.');
        }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $fractional = Fractional::findOrFail($id);
        $fractional->delete();

        return redirect()->route('fractionals.index')->with('success', 'Fractional eliminado correctamente.');
    }

    /**
     * Normaliza el valor recibido a formato "x,y x,y ...".
     * - Si viene JSON (e.g. [[x,y],[x,y]] o [{x:..,y:..}]), lo convierte a string.
     * - Si ya viene como string, limpia espacios, saltos de línea y puntos y comas.
     */
   private function normalizePoints(?string $raw): string
{
    if (!$raw) return '';

    // Si pegaron <polygon ... points="...">, extrae el contenido de points
    if (preg_match('/points\s*=\s*("|\')(.*?)\1/i', $raw, $m)) {
        $raw = $m[2];
    }

    // Limpieza genérica
    $raw = strip_tags($raw);
    $raw = str_ireplace(['points=', '"', "'"], '', $raw);
    $raw = preg_replace('/\s+/', ' ', trim($raw));

    return $raw;
}


// App\Http\Controllers\FractionalController.php
public function clone(Fractional $fractional)
{
    $copy = $fractional->replicate();
    $copy->name = $fractional->name.' (Copia)';
    // Si quieres forzar disponible:
    // $copy->status = 'available';
    $copy->push();

    return back()->with('success', 'Fractional clonado correctamente.');
}

}
