<?php

namespace App\Http\Controllers;

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

class PartnerController extends Controller
{
    public function index(Request $request)
    {
        $partners = Partner::latest()->paginate(10);

        if ($request->wantsJson()) {
            return response()->json($partners);
        }

        return view('partners.index', compact('partners'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:customer,supplier,both',
            'code' => 'required|string|unique:partners,code',
            'email' => 'nullable|email',
        ]);

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

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

    public function show(Partner $partner)
    {
        return view('partners.show', compact('partner'));
    }

    public function edit(Partner $partner)
    {
        return view('partners.edit', compact('partner'));
    }

    public function update(Request $request, Partner $partner)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:customer,supplier,both',
            'code' => 'required|string|unique:partners,code,' . $partner->id,
            'email' => 'nullable|email',
        ]);

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

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

    public function destroy(Partner $partner)
    {
        // Check for related orders
        if ($partner->purchaseOrders()->exists() || $partner->salesOrders()->exists()) {
            return back()->with('error', 'Cannot delete partner with existing orders.');
        }

        $partner->delete();
        return redirect()->route('partners.index')->with('success', 'Partner deleted.');
    }
}
