<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::all();

        $headers = ['Nama Produk', 'Harga', 'Harga Reseller', 'Tersedia Reseller', 'Aksi'];

        $rows = $products->map(function ($p) {
            return [
                'cols' => [
                    $p->name,
                    'Rp ' . number_format($p->price, 0, ',', '.'),
                    $p->reseller_price ? 'Rp ' . number_format($p->reseller_price, 0, ',', '.') : '-',
                    $p->available_for_reseller ? 'Ya' : 'Tidak',
                ],
                'actions' => view('components.action-button', [
                    'id' => $p->id,
                    'resource' => 'products'
                ])->render(),
            ];
        });

        return view('products.index', compact('headers', 'rows'));
    }

    public function create()
    {
        return view('products.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'description' => 'required|string',
            'price' => 'required|numeric|min:0',
            'reseller_price' => 'nullable|numeric|min:0',
            'available_for_reseller' => 'boolean',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('assets/img/contents'), $filename);
            $validated['image'] = 'assets/img/contents/' . $filename;
        }

        Product::create($validated);

        return redirect()->route('products.index')->with('success', 'Product created successfully');
    }

    public function show(Product $product)
    {
        return view('products.show', compact('product'));
    }

    public function edit(Product $product)
    {
        return view('products.edit', compact('product'));
    }

    public function update(Request $request, Product $product)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'description' => 'required|string',
            'price' => 'required|numeric|min:0',
            'reseller_price' => 'nullable|numeric|min:0',
            'available_for_reseller' => 'boolean',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'remove_image' => 'nullable|boolean'
        ]);

        if ($request->remove_image == 1) {
            if ($product->image && file_exists(public_path($product->image))) {
                unlink(public_path($product->image));
            }
            $validated['image'] = null;
        }

        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('assets/img/contents'), $filename);

            if ($product->image && file_exists(public_path($product->image))) {
                unlink(public_path($product->image));
            }

            $validated['image'] = 'assets/img/contents/' . $filename;
        }

        $product->update($validated);

        return redirect()->route('products.index')->with('success', 'Product updated successfully');
    }

    public function destroy(Product $product)
    {
        if ($product->image && file_exists(public_path($product->image))) {
            unlink(public_path($product->image));
        }

        $product->delete();

        return redirect()->route('products.index')->with('success', 'Product deleted successfully');
    }
}
