<?php

namespace App\Http\Controllers\Admin\Customer;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\CustomerBranch;
use Illuminate\Http\Request;
use Inertia\Inertia;
class CustomerBranchController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $customers = Client::orderBy('name', 'ASC')->get();
    
        return Inertia::render('Customer/CustomerBranch', compact('customers'));
    }


    /**
     * Get next branch code for a customer
     */
    public function getNextCode(Request $request)
    {
        $customerId = $request->input('customer_id');
        
        if ($customerId) {
            // Get last branch for this specific customer
            $lastBranch = CustomerBranch::where('customer_id', $customerId)
                ->orderBy('id', 'desc')
                ->first();
        } else {
            // Get last branch overall
            $lastBranch = CustomerBranch::orderBy('id', 'desc')->first();
        }
        
        $nextCode = generate_next_code($lastBranch, 'BR', 4, 'branch_code');
        
        return response()->json(['next_code' => $nextCode]);
    }

    /**
     * Get branches for a specific customer or all branches
     */
    public function view($customerId = null)
    {
        // Handle "all" as a special case to get all branches
        if ($customerId && $customerId !== 'all') {
            $branches = CustomerBranch::where('customer_id', $customerId)
                ->with('customer')
                ->orderBy('id', 'desc')
                ->get();
            $lastRecord = CustomerBranch::where('customer_id', $customerId)
                ->orderBy('id', 'DESC')
                ->first();
        } else {
            // Get all branches
            $branches = CustomerBranch::with('customer')
                ->orderBy('id', 'desc')
                ->get();
            $lastRecord = CustomerBranch::orderBy('id', 'DESC')->first();
        }
        
        $branchCode = generate_next_code($lastRecord, 'BR', 4, 'branch_code');

        return response()->json(['branches' => $branches, 'branchCode' => $branchCode]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'customer_id' => 'required|exists:clients,id',
            'branch_name' => 'required|string|max:255',
            'branch_code' => 'nullable|string|max:255|unique:customer_branches,branch_code',
            'contact_person' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255|unique:customer_branches,email',
            'address' => 'nullable|string',
            'status' => 'nullable|string|in:0,1',
        ]);

        // Auto-generate branch code if not provided
        $branchCode = $request->branch_code;
        if (empty($branchCode)) {
            $lastBranch = CustomerBranch::where('customer_id', $request->customer_id)
                ->orderBy('id', 'desc')
                ->first();
            $branchCode = generate_next_code($lastBranch, 'BR', 4, 'branch_code');
        }
        
        $branch = CustomerBranch::create([
            'customer_id' => $request->customer_id,
            'branch_name' => $request->branch_name,
            'branch_code' => $branchCode,
            'contact_person' => $request->contact_person,
            'phone' => $request->phone,
            'email' => $request->email,
            'address' => $request->address,
            'status' => $request->status ?? '1',
        ]);

    

        return response()->json([
            'success' => 'Branch created successfully',

        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $branch = CustomerBranch::findOrFail($id);
        
        $request->validate([
            'branch_name' => 'required|string|max:255',
            'branch_code' => 'nullable|string|max:255|unique:customer_branches,branch_code,' . $id,
            'contact_person' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255|unique:customer_branches,email,' . $id,
            'address' => 'nullable|string',
            'status' => 'nullable|string|in:0,1',
        ]);

        $branch = CustomerBranch::findOrFail($id);
        $branch->update($request->only([
            'branch_name',
            'branch_code',
            'contact_person',
            'phone',
            'email',
            'address',
            'status',
        ]));

     
        return response()->json([
            'success' => 'Branch updated successfully',
          
        ]);
    }

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

    
        return response()->json([
            'success' => 'Branch deleted successfully',
     
        ]);
    }
}
