<?php

namespace App\Http\Controllers\Api;

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

class PosCustomerController extends Controller
{
    use RestaurantBranchFilterTrait;
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = PosCustomer::query();
        
        // Apply restaurant and branch filtering
        $user = $request->user();
        $this->applyRestaurantBranchFilter($query, $user, $request);
        
        // Backward compatibility: Also filter by warehouse_id if provided
        if ($user && $user->warehouse_id && !$user->branch_id) {
            $query->where('warehouse_id', $user->warehouse_id);
        }
        
        // Search by name or phone
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }
        
        $customers = $query->orderBy('name')->paginate(20);
        
        return response()->json($customers);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:500',
            'email' => 'nullable|email|max:255',
            'notes' => 'nullable|string',
        ]);

        $user = $request->user();
        
        // Get restaurant and branch context
        $context = $this->getRestaurantBranchContext($user, $request);
        $branchId = $context['branch_id'] ?? $user->branch_id ?? null;
        $restaurantId = $context['restaurant_id'] ?? $user->restaurant_id ?? null;
        $warehouseId = $user->warehouse_id ?? $branchId ?? null;

        // Check if customer with same phone already exists
        if (!empty($validated['phone'])) {
            $existingQuery = PosCustomer::where('phone', $validated['phone']);
            if ($branchId) {
                $existingQuery->where('branch_id', $branchId);
            } elseif ($warehouseId) {
                $existingQuery->where('warehouse_id', $warehouseId);
            }
            $existingCustomer = $existingQuery->first();
            
            if ($existingCustomer) {
                return response()->json([
                    'message' => 'Customer with this phone number already exists',
                    'customer' => $existingCustomer
                ], 409);
            }
        }

        $customer = PosCustomer::create([
            'warehouse_id' => $warehouseId, // Backward compatibility
            'branch_id' => $branchId,
            'restaurant_id' => $restaurantId,
            'name' => $validated['name'],
            'phone' => $validated['phone'] ?? null,
            'address' => $validated['address'] ?? null,
            'email' => $validated['email'] ?? null,
            'notes' => $validated['notes'] ?? null,
        ]);

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

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $customer = PosCustomer::findOrFail($id);
        return response()->json($customer);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $customer = PosCustomer::findOrFail($id);
        
        $validated = $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:500',
            'email' => 'nullable|email|max:255',
            'notes' => 'nullable|string',
        ]);

        // Check if phone is being changed and already exists
        if (!empty($validated['phone']) && $validated['phone'] !== $customer->phone) {
            $existingCustomer = PosCustomer::where('phone', $validated['phone'])
                ->where('warehouse_id', $customer->warehouse_id)
                ->where('id', '!=', $id)
                ->first();
            
            if ($existingCustomer) {
                return response()->json([
                    'message' => 'Customer with this phone number already exists'
                ], 409);
            }
        }

        $customer->update($validated);

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

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

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