<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Helpers\RestaurantBranchFilterTrait;
use App\Models\Supplier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SupplierController extends Controller
{
    use RestaurantBranchFilterTrait;

    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    public function index(Request $request)
    {
        $user = $request->user();
        $query = Supplier::query();

        // Apply restaurant filtering
        if ($user->isAdmin()) {
            if ($request->has('restaurant_id') && $request->restaurant_id) {
                $query->where('restaurant_id', $request->restaurant_id);
            } else {
                return response()->json(['data' => []]);
            }
        } elseif ($user->isInventoryManager() && $user->restaurant_id) {
            // Inventory manager: filter by their restaurant
            $query->where('restaurant_id', $user->restaurant_id);
        } elseif ($user->isRestaurantOwner() && $user->restaurant_id) {
            $query->where('restaurant_id', $user->restaurant_id);
        } elseif ($user->isBranchManager() && $user->branch_id) {
            // Get restaurant_id from branch
            $branch = \App\Models\Branch::find($user->branch_id);
            if ($branch && $branch->restaurant_id) {
                $query->where('restaurant_id', $branch->restaurant_id);
            } else {
                return response()->json(['data' => []]);
            }
        } else {
            return response()->json(['data' => []]);
        }

        // Filter by status
        if ($request->has('status')) {
            $query->where('status', $request->status);
        } else {
            $query->where('status', 'active');
        }

        // Search
        if ($request->has('search')) {
            $query->where(function($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%')
                  ->orWhere('email', 'like', '%' . $request->search . '%')
                  ->orWhere('phone', 'like', '%' . $request->search . '%');
            });
        }

        $suppliers = $query->orderBy('name')->get();

        return response()->json(['data' => $suppliers]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:255',
            'address' => 'nullable|string',
            'contact_person' => 'nullable|string|max:255',
            'notes' => 'nullable|string',
        ]);

        $user = $request->user();

        // Determine restaurant_id
        $restaurantId = null;
        if ($user->isAdmin()) {
            if (!$request->has('restaurant_id') || !$request->restaurant_id) {
                return response()->json(['error' => 'Restaurant selection is required'], 400);
            }
            $restaurantId = $request->restaurant_id;
        } elseif ($user->isInventoryManager() && $user->restaurant_id) {
            // Inventory manager: use their assigned restaurant_id
            $restaurantId = $user->restaurant_id;
        } elseif ($user->isRestaurantOwner() && $user->restaurant_id) {
            $restaurantId = $user->restaurant_id;
        } elseif ($user->isBranchManager() && $user->branch_id) {
            $branch = \App\Models\Branch::find($user->branch_id);
            if ($branch && $branch->restaurant_id) {
                $restaurantId = $branch->restaurant_id;
            } else {
                return response()->json(['error' => 'Branch not found'], 400);
            }
        } else {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        // Check for duplicate name
        $existing = Supplier::where('restaurant_id', $restaurantId)
            ->where('name', $validated['name'])
            ->first();

        if ($existing) {
            return response()->json(['error' => 'Supplier with this name already exists'], 422);
        }

        $supplier = Supplier::create([
            ...$validated,
            'restaurant_id' => $restaurantId,
            'status' => 'active',
            'created_by' => $user->id,
        ]);

        return response()->json($supplier, 201);
    }

    public function show(Supplier $supplier)
    {
        $user = request()->user();

        // Verify access
        if ($user->isAdmin()) {
            // Admin can view any supplier
        } elseif ($user->isInventoryManager() && $user->restaurant_id) {
            // Inventory manager: verify supplier belongs to their restaurant
            $supplierRestaurantId = (int) $supplier->restaurant_id;
            $userRestaurantId = (int) $user->restaurant_id;
            if ($supplierRestaurantId !== $userRestaurantId) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
        } elseif ($user->isRestaurantOwner() && $user->restaurant_id) {
            $supplierRestaurantId = (int) $supplier->restaurant_id;
            $userRestaurantId = (int) $user->restaurant_id;
            if ($supplierRestaurantId !== $userRestaurantId) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
        } elseif ($user->isBranchManager() && $user->branch_id) {
            $branch = \App\Models\Branch::find($user->branch_id);
            if (!$branch) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
            $supplierRestaurantId = (int) $supplier->restaurant_id;
            $branchRestaurantId = (int) $branch->restaurant_id;
            if ($supplierRestaurantId !== $branchRestaurantId) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
        } else {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        return response()->json($supplier);
    }

    public function update(Request $request, Supplier $supplier)
    {
        $user = request()->user();

        // Verify access
        if ($user->isAdmin()) {
            // Admin can update any supplier
        } elseif ($user->isInventoryManager() && $user->restaurant_id) {
            // Inventory manager: verify supplier belongs to their restaurant
            $supplierRestaurantId = (int) $supplier->restaurant_id;
            $userRestaurantId = (int) $user->restaurant_id;
            if ($supplierRestaurantId !== $userRestaurantId) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
        } elseif ($user->isRestaurantOwner() && $user->restaurant_id) {
            $supplierRestaurantId = (int) $supplier->restaurant_id;
            $userRestaurantId = (int) $user->restaurant_id;
            if ($supplierRestaurantId !== $userRestaurantId) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
        } elseif ($user->isBranchManager() && $user->branch_id) {
            $branch = \App\Models\Branch::find($user->branch_id);
            if (!$branch) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
            $supplierRestaurantId = (int) $supplier->restaurant_id;
            $branchRestaurantId = (int) $branch->restaurant_id;
            if ($supplierRestaurantId !== $branchRestaurantId) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
        } else {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:255',
            'address' => 'nullable|string',
            'contact_person' => 'nullable|string|max:255',
            'notes' => 'nullable|string',
            'status' => 'nullable|in:active,inactive',
        ]);

        // Check for duplicate name (excluding current supplier)
        $existing = Supplier::where('restaurant_id', $supplier->restaurant_id)
            ->where('name', $validated['name'])
            ->where('id', '!=', $supplier->id)
            ->first();

        if ($existing) {
            return response()->json(['error' => 'Supplier with this name already exists'], 422);
        }

        $supplier->update($validated);

        return response()->json($supplier);
    }

    public function destroy(Supplier $supplier)
    {
        $user = request()->user();

        // Verify access
        if ($user->isAdmin()) {
            // Admin can delete any supplier
        } elseif ($user->isInventoryManager() && $user->restaurant_id) {
            // Inventory manager: verify supplier belongs to their restaurant
            $supplierRestaurantId = (int) $supplier->restaurant_id;
            $userRestaurantId = (int) $user->restaurant_id;
            if ($supplierRestaurantId !== $userRestaurantId) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
        } elseif ($user->isRestaurantOwner() && $user->restaurant_id) {
            $supplierRestaurantId = (int) $supplier->restaurant_id;
            $userRestaurantId = (int) $user->restaurant_id;
            if ($supplierRestaurantId !== $userRestaurantId) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
        } elseif ($user->isBranchManager() && $user->branch_id) {
            $branch = \App\Models\Branch::find($user->branch_id);
            if (!$branch) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
            $supplierRestaurantId = (int) $supplier->restaurant_id;
            $branchRestaurantId = (int) $branch->restaurant_id;
            if ($supplierRestaurantId !== $branchRestaurantId) {
                return response()->json(['error' => 'Unauthorized'], 403);
            }
        } else {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        // Check if supplier has associated bills
        $hasBills = \App\Models\SupplierBill::where('supplier_id', $supplier->id)->exists();
        if ($hasBills) {
            // Soft delete by setting status to inactive
            $supplier->update(['status' => 'inactive']);
            return response()->json(['message' => 'Supplier deactivated successfully (has associated bills)']);
        }

        $supplier->delete();

        return response()->json(['message' => 'Supplier deleted successfully']);
    }
}
