<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Supplier;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class SupplierController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): View
    {
        $perPage = $request->get('per_page', 10);
        $search = $request->get('search', '');

        $query = Supplier::query();

        if (! empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        $suppliers = $query->orderBy('created_at', 'desc')->paginate($perPage);

        return view('admin.suppliers.index', [
            'suppliers' => $suppliers,
            'perPage' => $perPage,
            'search' => $search,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        // Merge defaults before validation
        $request->merge([
            'balance' => $request->input('balance', '0'),
            'mode' => $request->input('mode', 'credit'),
        ]);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'required|string|max:20',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:5120',
            'balance' => 'nullable|numeric|min:0',
            'mode' => 'required|in:credit,debit',
            'address' => 'nullable|string',
            'city' => 'nullable|string|max:100',
            'state' => 'nullable|string|max:100',
            'zip' => 'nullable|string|max:20',
            'country' => 'nullable|string|max:100',
            'tax_id' => 'nullable|string|max:50',
            'notes' => 'nullable|string',
        ], [
            'name.required' => 'The name field is required.',
            'phone.required' => 'The phone number field is required.',
            'mode.required' => 'Please select a mode (Credit or Debit).',
            'mode.in' => 'Mode must be either Credit or Debit.',
            'email.email' => 'Please enter a valid email address.',
            'image.image' => 'The uploaded file must be an image.',
            'image.max' => 'The image size must not exceed 5MB.',
        ]);

        try {
            // Handle image upload
            $imagePath = null;
            if ($request->hasFile('image')) {
                $image = $request->file('image');
                $imagePath = $image->store('suppliers', 'public');
            }

            $supplier = Supplier::create([
                'name' => $validated['name'],
                'email' => $validated['email'] ?? null,
                'phone' => (string) $validated['phone'],
                'image' => $imagePath,
                'balance' => floatval($validated['balance'] ?? 0),
                'mode' => $validated['mode'],
                'address' => $validated['address'] ?? null,
                'city' => $validated['city'] ?? null,
                'state' => $validated['state'] ?? null,
                'zip' => $validated['zip'] ?? null,
                'country' => $validated['country'] ?? null,
                'tax_id' => $validated['tax_id'] ?? null,
                'notes' => $validated['notes'] ?? null,
                'is_active' => true,
                'created_by' => Auth::id(),
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Supplier created successfully',
                'supplier' => $supplier->load('creator'),
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error creating supplier: '.$e->getMessage(),
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Supplier $supplier): View
    {
        return view('admin.suppliers.edit', [
            'supplier' => $supplier,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Supplier $supplier): RedirectResponse
    {
        // Merge defaults before validation
        $request->merge([
            'balance' => $request->input('balance', '0'),
            'mode' => $request->input('mode', 'credit'),
        ]);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'required|string|max:20',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:5120',
            'balance' => 'nullable|numeric|min:0',
            'mode' => 'required|in:credit,debit',
            'address' => 'nullable|string',
            'city' => 'nullable|string|max:100',
            'state' => 'nullable|string|max:100',
            'zip' => 'nullable|string|max:20',
            'country' => 'nullable|string|max:100',
            'tax_id' => 'nullable|string|max:50',
            'notes' => 'nullable|string',
        ], [
            'name.required' => 'The name field is required.',
            'phone.required' => 'The phone number field is required.',
            'mode.required' => 'Please select a mode (Credit or Debit).',
            'mode.in' => 'Mode must be either Credit or Debit.',
            'email.email' => 'Please enter a valid email address.',
            'image.image' => 'The uploaded file must be an image.',
            'image.max' => 'The image size must not exceed 5MB.',
        ]);

        try {
            // Handle image upload
            if ($request->hasFile('image')) {
                // Delete old image if exists
                if ($supplier->image && Storage::disk('public')->exists($supplier->image)) {
                    Storage::disk('public')->delete($supplier->image);
                }

                $image = $request->file('image');
                $imagePath = $image->store('suppliers', 'public');
                $validated['image'] = $imagePath;
            } else {
                // Keep existing image if no new image uploaded
                $validated['image'] = $supplier->image;
            }

            $supplier->update([
                'name' => $validated['name'],
                'email' => $validated['email'] ?? null,
                'phone' => (string) $validated['phone'],
                'image' => $validated['image'] ?? null,
                'balance' => floatval($validated['balance'] ?? 0),
                'mode' => $validated['mode'],
                'address' => $validated['address'] ?? null,
                'city' => $validated['city'] ?? null,
                'state' => $validated['state'] ?? null,
                'zip' => $validated['zip'] ?? null,
                'country' => $validated['country'] ?? null,
                'tax_id' => $validated['tax_id'] ?? null,
                'notes' => $validated['notes'] ?? null,
            ]);

            return redirect()->route('admin.suppliers.index')
                ->with('success', 'Supplier updated successfully');
        } catch (\Exception $e) {
            return back()
                ->withInput()
                ->withErrors(['error' => 'Error updating supplier: '.$e->getMessage()]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            $supplier = Supplier::findOrFail($id);
            $supplier->delete();

            return response()->json([
                'success' => true,
                'message' => 'Supplier deleted successfully',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error deleting supplier: '.$e->getMessage(),
            ], 500);
        }
    }
}
