<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Material;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function __construct()
    {
        $this->middleware(\App\Http\Middleware\PermissionMiddleware::class . ':create products')->only(['create', 'store']);
        $this->middleware(\App\Http\Middleware\PermissionMiddleware::class . ':edit products')->only(['edit', 'update']);
        $this->middleware(\App\Http\Middleware\PermissionMiddleware::class . ':delete products')->only(['destroy']);
    }
    public function index(Request $request)
    {
        $query = Product::with('materials');

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('code', 'like', "%{$search}%");
            });
        }

        if ($request->filled('status')) {
            $query->where('is_active', $request->status === 'active');
        }

        $products = $query->latest()->paginate(15)->withQueryString();

        return view('pages.products.items.index', [
            'title' => 'Kelola Produk',
            'products' => $products,
        ]);
    }

    public function create()
    {
        $materials = Material::active()->orderBy('name')->get();
        
        // Pre-format for JSON to avoid blade parsing issues
        $materialsJson = $materials->map(function($m) {
            return [
                'id' => $m->id,
                'name' => $m->name,
                'base_price' => $m->base_price,
                'unit' => $m->unit,
                'category' => $m->category
            ];
        });

        return view('pages.products.items.create', [
            'title' => 'Tambah Produk',
            'materials' => $materials,
            'materialsJson' => $materialsJson,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'code' => ['nullable', 'string', 'max:50', 'unique:products,code'],
            'description' => ['nullable', 'string', 'max:1000'],
            'is_active' => ['boolean'],
            'track_clicks' => ['boolean'],
            'material_ids' => ['nullable', 'array'],
            'material_ids.*' => ['exists:materials,id'],
        ]);

        $product = Product::create([
            'name' => $validated['name'],
            'code' => $validated['code'] ?? Product::generateCode($validated['name']),
            'description' => $validated['description'] ?? null,
            'is_active' => $validated['is_active'] ?? true,
            'track_clicks' => $request->boolean('track_clicks'),
        ]);

        // Attach materials if provided
        if (!empty($validated['material_ids'])) {
            $product->materials()->sync($validated['material_ids']);
        }

        return redirect()->route('products.items.index')
            ->with('success', 'Produk berhasil ditambahkan.');
    }

    public function edit(Product $product)
    {
        $product->load('materials');
        $materials = Material::active()->orderBy('name')->get();
        
        // Pre-format for JSON to avoid blade parsing issues
        $materialsJson = $materials->map(function($m) {
            return [
                'id' => $m->id,
                'name' => $m->name,
                'base_price' => $m->base_price,
                'unit' => $m->unit,
                'category' => $m->category
            ];
        });
        
        $selectedMaterialIds = $product->materials->pluck('id')->toArray();

        return view('pages.products.items.edit', [
            'title' => 'Edit Produk',
            'product' => $product,
            'materials' => $materials,
            'materialsJson' => $materialsJson,
            'selectedMaterialIds' => $selectedMaterialIds,
        ]);
    }

    public function update(Request $request, Product $product)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'code' => ['nullable', 'string', 'max:50', 'unique:products,code,' . $product->id],
            'description' => ['nullable', 'string', 'max:1000'],
            'is_active' => ['boolean'],
            'track_clicks' => ['boolean'],
            'material_ids' => ['nullable', 'array'],
            'material_ids.*' => ['exists:materials,id'],
        ]);

        $product->update([
            'name' => $validated['name'],
            'code' => $validated['code'] ?? $product->code,
            'description' => $validated['description'] ?? null,
            'is_active' => $validated['is_active'] ?? true,
            'track_clicks' => $request->boolean('track_clicks'),
        ]);

        // Sync materials
        $product->materials()->sync($validated['material_ids'] ?? []);

        return redirect()->route('products.items.index')
            ->with('success', 'Produk berhasil diperbarui.');
    }

    public function destroy(Product $product)
    {
        // Check if product has order items
        if ($product->orderItems()->count() > 0) {
            return back()->with('error', 'Produk tidak dapat dihapus karena sudah digunakan dalam order.');
        }

        $product->delete();

        return redirect()->route('products.items.index')
            ->with('success', 'Produk berhasil dihapus.');
    }

    /**
     * API endpoint to get materials for a specific product.
     */
    public function getMaterials(Product $product)
    {
        // If product has specific materials, return those
        if ($product->hasMaterials()) {
            $materials = $product->materials()->with('prices')->active()->get();
        } else {
            // Otherwise return all active materials
            $materials = Material::with('prices')->active()->orderBy('name')->get();
        }

        return response()->json($materials->map(function ($m) {
            return [
                'id' => $m->id,
                'name' => $m->name,
                'base_price' => $m->base_price,
                'unit' => $m->unit,
                'prices' => $m->prices->map(function($p) {
                    return [
                        'member_type' => $p->member_type,
                        'sisi' => $p->sisi,
                        'min_qty' => $p->min_qty,
                        'max_qty' => $p->max_qty,
                        'price' => floatval($p->price),
                    ];
                })->values(),
            ];
        }));
    }
}
