<?php

namespace App\Http\Controllers;

use App\Models\Item;
use App\Models\ItemVariation;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class VariationsController extends Controller
{
    public function index()
    {
        return view('variations.index');
    }

    public function create()
    {
        $items = Item::where('is_active', true)->orderBy('name')->get();
        return view('variations.create', compact('items'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'item_id' => 'required|exists:items,id',
            'name' => 'required|string|max:255',
            'sku_suffix' => 'nullable|string|max:255',
            'size' => 'nullable|string|max:100',
            'color' => 'nullable|string|max:100',
            'unit' => 'nullable|string|max:50',
            'length' => 'nullable|numeric|min:0|max:999999.99',
            'width' => 'nullable|numeric|min:0|max:999999.99',
            'height' => 'nullable|numeric|min:0|max:999999.99',
            'weight' => 'nullable|numeric|min:0|max:999999.99',
            'weight_unit' => 'nullable|string|in:kg,g,lb,oz',
            'cost_price' => 'nullable|numeric|min:0|max:999999.9999',
            'selling_price' => 'nullable|numeric|min:0|max:999999.9999',
            'is_active' => 'boolean',
            'description' => 'nullable|string|max:1000',
        ]);

        $variation = ItemVariation::create($request->all());

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

    public function show(ItemVariation $variation)
    {
        $variation->load(['item', 'inventories', 'itemSuppliers']);
        return view('variations.show', compact('variation'));
    }

    public function edit(ItemVariation $variation)
    {
        $items = Item::where('is_active', true)->orderBy('name')->get();
        return view('variations.edit', compact('variation', 'items'));
    }

    public function update(Request $request, ItemVariation $variation)
    {
        $request->validate([
            'item_id' => 'required|exists:items,id',
            'name' => 'required|string|max:255',
            'sku_suffix' => 'nullable|string|max:255',
            'size' => 'nullable|string|max:100',
            'color' => 'nullable|string|max:100',
            'unit' => 'nullable|string|max:50',
            'length' => 'nullable|numeric|min:0|max:999999.99',
            'width' => 'nullable|numeric|min:0|max:999999.99',
            'height' => 'nullable|numeric|min:0|max:999999.99',
            'weight' => 'nullable|numeric|min:0|max:999999.99',
            'weight_unit' => 'nullable|string|in:kg,g,lb,oz',
            'cost_price' => 'nullable|numeric|min:0|max:999999.9999',
            'selling_price' => 'nullable|numeric|min:0|max:999999.9999',
            'is_active' => 'boolean',
            'description' => 'nullable|string|max:1000',
        ]);

        $variation->update($request->all());

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

    public function destroy(ItemVariation $variation)
    {
        $variation->delete();

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

    public function getData()
    {
        $variations = ItemVariation::with(['item'])
            ->orderBy('item_id')
            ->orderBy('name')
            ->get();

        return DataTables::of($variations)
            ->addColumn('item_name', function ($variation) {
                return $variation->item->name ?? 'N/A';
            })
            ->addColumn('item_sku', function ($variation) {
                return $variation->item->sku ?? 'N/A';
            })
            ->addColumn('full_sku', function ($variation) {
                return $variation->full_sku;
            })
            ->addColumn('dimensions', function ($variation) {
                return $variation->dimensions ?: '-';
            })
            ->addColumn('weight_display', function ($variation) {
                return $variation->formatted_weight;
            })
            ->addColumn('cost_price_display', function ($variation) {
                return $variation->formatted_cost_price;
            })
            ->addColumn('selling_price_display', function ($variation) {
                return $variation->formatted_selling_price;
            })
            ->addColumn('stock_info', function ($variation) {
                $total = $variation->total_stock;
                $available = $variation->available_stock;
                return "Total: {$total} | Available: {$available}";
            })
            ->addColumn('status_badge', function ($variation) {
                return $variation->status_badge;
            })
            ->addColumn('actions', function ($variation) {
                $actions = '<div class="btn-group" role="group">';
                $actions .= '<a href="' . route('variations.show', $variation->id) . '" class="btn btn-sm btn-info">View</a>';
                $actions .= '<a href="' . route('variations.edit', $variation->id) . '" class="btn btn-sm btn-warning">Edit</a>';
                $actions .= '<form method="POST" action="' . route('variations.destroy', $variation->id) . '" style="display:inline;">';
                $actions .= csrf_field() . method_field('DELETE');
                $actions .= '<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm(\'Are you sure you want to delete this variation?\')">Delete</button>';
                $actions .= '</form>';
                $actions .= '</div>';
                return $actions;
            })
            ->rawColumns(['status_badge', 'actions'])
            ->make(true);
    }

    public function toggleActive(ItemVariation $variation)
    {
        $variation->update(['is_active' => !$variation->is_active]);

        $status = $variation->is_active ? 'activated' : 'deactivated';

        return redirect()->route('variations.index')
            ->with('success', "Variation {$status} successfully.");
    }
}
