<?php

namespace App\Http\Controllers;

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

class ItemSupplierController extends Controller
{
    public function index()
    {
        return view('item_suppliers.index');
    }

    public function create()
    {
        $items = Item::where('is_active', true)->get();
        $suppliers = Contact::vendor()->where('is_active', true)->get();
        return view('item_suppliers.create', compact('items', 'suppliers'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'item_id' => 'required|exists:items,id',
            'contact_id' => 'required|exists:contacts,id',
            'is_primary' => 'boolean',
            'lead_time_days' => 'nullable|integer|min:0',
            'min_order_qty' => 'nullable|numeric|min:0',
            'last_price' => 'nullable|numeric|min:0'
        ]);

        // If setting as primary, unset other primary suppliers for this item
        if ($request->is_primary) {
            ItemSupplier::where('item_id', $request->item_id)
                ->where('is_primary', true)
                ->update(['is_primary' => false]);
        }

        ItemSupplier::create($request->all());

        return redirect()->route('item-suppliers.index')
            ->with('success', 'Item supplier relationship created successfully.');
    }

    public function show(ItemSupplier $item_supplier)
    {
        $item_supplier->load(['item', 'contact']);
        return view('item_suppliers.show', compact('item_supplier'));
    }

    public function edit(ItemSupplier $item_supplier)
    {
        $items = Item::where('is_active', true)->get();
        $suppliers = Contact::vendor()->where('is_active', true)->get();
        return view('item_suppliers.edit', compact('item_supplier', 'items', 'suppliers'));
    }

    public function update(Request $request, ItemSupplier $item_supplier)
    {
        $request->validate([
            'item_id' => 'required|exists:items,id',
            'contact_id' => 'required|exists:contacts,id',
            'is_primary' => 'boolean',
            'lead_time_days' => 'nullable|integer|min:0',
            'min_order_qty' => 'nullable|numeric|min:0',
            'last_price' => 'nullable|numeric|min:0'
        ]);

        // If setting as primary, unset other primary suppliers for this item
        if ($request->is_primary) {
            ItemSupplier::where('item_id', $request->item_id)
                ->where('id', '!=', $item_supplier->id)
                ->where('is_primary', true)
                ->update(['is_primary' => false]);
        }

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

        return redirect()->route('item-suppliers.index')
            ->with('success', 'Item supplier relationship updated successfully.');
    }

    public function destroy(ItemSupplier $item_supplier)
    {
        $item_supplier->delete();

        return redirect()->route('item-suppliers.index')
            ->with('success', 'Item supplier relationship deleted successfully.');
    }

    public function getData()
    {
        $itemSuppliers = ItemSupplier::with(['item', 'contact'])
            ->orderBy('item_id')
            ->orderBy('is_primary', 'desc')
            ->get();

        return DataTables::of($itemSuppliers)
            ->addColumn('item_name', function ($itemSupplier) {
                return $itemSupplier->item->name ?? 'N/A';
            })
            ->addColumn('item_code', function ($itemSupplier) {
                return $itemSupplier->item->sku ?? 'N/A';
            })
            ->addColumn('supplier_name', function ($itemSupplier) {
                return $itemSupplier->contact->name ?? 'N/A';
            })
            ->addColumn('supplier_code', function ($itemSupplier) {
                return $itemSupplier->contact->code ?? 'N/A';
            })
            ->addColumn('primary_badge', function ($itemSupplier) {
                return $itemSupplier->is_primary
                    ? '<span class="badge badge-success">Primary</span>'
                    : '<span class="badge badge-secondary">Secondary</span>';
            })
            ->addColumn('lead_time', function ($itemSupplier) {
                return $itemSupplier->lead_time_days ? $itemSupplier->lead_time_days . ' days' : 'N/A';
            })
            ->addColumn('min_order', function ($itemSupplier) {
                return $itemSupplier->min_order_qty ? number_format($itemSupplier->min_order_qty, 2) : 'N/A';
            })
            ->addColumn('last_price', function ($itemSupplier) {
                return $itemSupplier->last_price ? 'PKR ' . number_format($itemSupplier->last_price, 2) : 'N/A';
            })
            ->addColumn('actions', function ($itemSupplier) {
                $actions = '<div class="btn-group" role="group">';
                $actions .= '<a href="' . route('item-suppliers.show', $itemSupplier->id) . '" class="btn btn-sm btn-info">View</a>';
                $actions .= '<a href="' . route('item-suppliers.edit', $itemSupplier->id) . '" class="btn btn-sm btn-warning">Edit</a>';
                $actions .= '<form method="POST" action="' . route('item-suppliers.destroy', $itemSupplier->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?\')">Delete</button>';
                $actions .= '</form>';
                $actions .= '</div>';
                return $actions;
            })
            ->rawColumns(['primary_badge', 'actions'])
            ->make(true);
    }
}
