<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\Restaurant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class BranchSelectionController extends Controller
{
    /**
     * Select active branch for restaurant owner
     */
    public function selectBranch(Request $request)
    {
        $request->validate([
            'branch_id' => 'required|exists:branches,id',
        ]);

        $user = $request->user();

        // Only restaurant owners need to select branches
        if (!$user->isRestaurantOwner()) {
            return response()->json([
                'message' => 'Only restaurant owners can select branches'
            ], 403);
        }

        $branch = Branch::where('id', $request->branch_id)
            ->where('restaurant_id', $user->restaurant_id)
            ->first();

        if (!$branch) {
            return response()->json([
                'message' => 'Branch not found or does not belong to your restaurant'
            ], 404);
        }

        // Store selected branch and restaurant in session
        session([
            'selected_branch_id' => $branch->id,
            'branch_id' => $branch->id,
            'restaurant_id' => $branch->restaurant_id
        ]);

        return response()->json([
            'message' => 'Branch selected successfully',
            'branch' => [
                'id' => $branch->id,
                'name' => $branch->name,
                'code' => $branch->code,
                'logo' => $branch->logo,
            ]
        ]);
    }

    /**
     * Get currently selected branch
     */
    public function getCurrentBranch(Request $request)
    {
        $user = $request->user();

        if ($user->isRestaurantOwner()) {
            $branchId = session('selected_branch_id');
            if ($branchId) {
                $branch = Branch::where('id', $branchId)
                    ->where('restaurant_id', $user->restaurant_id)
                    ->first();
                
                if ($branch) {
                    return response()->json([
                        'branch' => [
                            'id' => $branch->id,
                            'name' => $branch->name,
                            'code' => $branch->code,
                            'logo' => $branch->logo,
                        ]
                    ]);
                }
            }
            return response()->json(['branch' => null]);
        }

        // For branch managers and staff, return their assigned branch
        if ($user->branch_id) {
            $branch = $user->branch;
            if ($branch) {
                return response()->json([
                    'branch' => [
                        'id' => $branch->id,
                        'name' => $branch->name,
                        'code' => $branch->code,
                        'logo' => $branch->logo,
                    ]
                ]);
            }
        }

        return response()->json(['branch' => null]);
    }

    /**
     * List branches for restaurant owner
     */
    public function listBranches(Request $request)
    {
        $user = $request->user();
        $query = Branch::query();

        // Restaurant owners see all branches of their restaurant
        if ($user->isRestaurantOwner() && $user->restaurant_id) {
            $query->where('restaurant_id', $user->restaurant_id);
        }
        // Branch managers see only their branch
        elseif ($user->isBranchManager() && $user->branch_id) {
            $query->where('id', $user->branch_id);
        }
        // Staff see their assigned branch
        elseif ($user->branch_id) {
            $query->where('id', $user->branch_id);
        }
        // Admin can see all or filter by restaurant
        elseif ($user->isAdmin()) {
            if ($request->has('restaurant_id')) {
                $query->where('restaurant_id', $request->restaurant_id);
            }
        }

        // Filter by status if provided
        if ($request->has('status')) {
            $query->where('status', $request->status);
        } elseif (!$user->isAdmin()) {
            // For non-admin users, default to active branches
            $query->where('status', 'active');
        }

        // Get branches with restaurant relationship
        $branches = $query->with('restaurant')->orderBy('name')->get();

        // Transform branches to include logo URL and match expected format
        $branchesList = $branches->map(function ($branch) {
            $branchData = [
                'id' => $branch->id,
                'name' => $branch->name,
                'code' => $branch->code,
                'logo' => $branch->logo,
                'address' => $branch->address,
                'status' => $branch->status,
                'restaurant_id' => $branch->restaurant_id,
            ];
            
            // Add logo URL if exists
            if ($branch->logo) {
                $branchData['logo_url'] = Storage::disk('public')->url($branch->logo);
            }
            
            // Add restaurant info if loaded
            if ($branch->relationLoaded('restaurant') && $branch->restaurant) {
                $branchData['restaurant'] = [
                    'id' => $branch->restaurant->id,
                    'name' => $branch->restaurant->name,
                ];
            }
            
            return $branchData;
        });

        // Return in paginated format to match BranchController::index format
        // This allows the frontend to handle both formats
        $perPage = $request->get('per_page', 50);
        $page = $request->get('page', 1);
        $total = $branchesList->count();
        $offset = ($page - 1) * $perPage;
        $items = $branchesList->slice($offset, $perPage)->values();

        return response()->json([
            'data' => $items,
            'current_page' => (int) $page,
            'per_page' => (int) $perPage,
            'total' => $total,
            'last_page' => (int) ceil($total / $perPage),
            // Also include branches key for backward compatibility
            'branches' => $items,
        ]);
    }
}
