<?php

namespace App\Http\Controllers;

use App\Models\BranchMaster;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;

class BranchMasterController extends Controller
{

public function index(Request $request)
{
    try {

        $query = BranchMaster::query();

        
        if ($request->filled('search')) {

            $search = $request->search;

            $query->where(function ($q) use ($search) {

                $q->where('Br_Name', 'like', "%$search%")
                  ->orWhere('Br_Code', 'like', "%$search%")
                  ->orWhere('Br_City', 'like', "%$search%")
                  ->orWhere('Br_State', 'like', "%$search%")
                  ->orWhere('Br_Email', 'like', "%$search%")
                  ->orWhere('Br_Mobile', 'like', "%$search%");
            });
        }

        
        $perPage = $request->get('per_page', 10);

        $branches = $query->orderBy('Br_Id', 'desc')
                          ->paginate($perPage);

        return response()->json([
            'success' => true,
            'message' => 'Branches retrieved successfully',
            'data' => $branches
        ], Response::HTTP_OK);

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'message' => 'Failed to retrieve branches',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], Response::HTTP_INTERNAL_SERVER_ERROR);
    }
}

public function all(Request $request)
{
    try {

        $query = BranchMaster::query();

        if ($request->filled('search')) {

            $search = $request->search;

            $query->where(function ($q) use ($search) {

                $q->where('Br_Name', 'like', "%$search%")
                  ->orWhere('Br_Code', 'like', "%$search%")
                  ->orWhere('Br_City', 'like', "%$search%")
                  ->orWhere('Br_State', 'like', "%$search%")
                  ->orWhere('Br_Email', 'like', "%$search%")
                  ->orWhere('Br_Mobile', 'like', "%$search%");
            });
        }

        $branches = $query->orderBy('Br_Id', 'desc')->get();

        return response()->json([
            'success' => true,
            'message' => 'All branches retrieved successfully',
            'data' => $branches
        ]);

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'message' => 'Failed to retrieve branches',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}

    public function store(Request $request)
    {
        try {

            $validator = Validator::make($request->all(), BranchMaster::createRules());

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], Response::HTTP_BAD_REQUEST);
            }

            $data = $validator->validated();

            if ($request->hasFile('Br_Logo')) {

                $file = $request->file('Br_Logo');
                $imageName = time().'_'.uniqid().'.'.$file->getClientOriginalExtension();

                $folder = public_path('branch/logo');

                if (!file_exists($folder)) {
                    mkdir($folder, 0755, true);
                }

                $file->move($folder, $imageName);

                $data['Br_Logo'] = url('branch/logo/'.$imageName);
            }

            $branch = BranchMaster::create($data);

            return response()->json([
                'success' => true,
                'message' => 'Branch created successfully',
                'data' => $branch
            ], Response::HTTP_CREATED);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Failed to create branch',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }


    public function show($id)
    {
        try {

            $branch = BranchMaster::find($id);

            if (!$branch) {
                return response()->json([
                    'success' => false,
                    'message' => 'Branch not found'
                ], Response::HTTP_NOT_FOUND);
            }

            return response()->json([
                'success' => true,
                'message' => 'Branch retrieved successfully',
                'data' => $branch
            ], Response::HTTP_OK);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve branch',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }


    public function update(Request $request, $id)
    {
        try {

            $branch = BranchMaster::find($id);

            if (!$branch) {
                return response()->json([
                    'success' => false,
                    'message' => 'Branch not found'
                ], Response::HTTP_NOT_FOUND);
            }

            $validator = Validator::make($request->all(), BranchMaster::updateRules($id));

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation error',
                    'errors' => $validator->errors()
                ], Response::HTTP_BAD_REQUEST);
            }

            $data = $validator->validated();

            if ($request->filled('Br_Logo')) {

                if ($branch->Br_Logo) {
                    $oldPath = public_path(str_replace(url('/').'/', '', $branch->Br_Logo));
                    if (file_exists($oldPath)) {
                        unlink($oldPath);
                    }
                }

                $imageName = null;

                if (str_contains($request->Br_Logo, 'base64')) {

                    $base64 = preg_replace('#^data:image/\w+;base64,#i', '', $request->Br_Logo);
                    $image = base64_decode($base64);

                    $imageName = 'branch_'.time().'_'.uniqid().'.png';

                    $folder = public_path('branch/logo');

                    if (!file_exists($folder)) {
                        mkdir($folder, 0755, true);
                    }

                    file_put_contents($folder.'/'.$imageName, $image);
                }
                elseif ($request->hasFile('Br_Logo')) {

                    $file = $request->file('Br_Logo');

                    $imageName = 'branch_'.time().'_'.uniqid().'.'.$file->getClientOriginalExtension();

                    $folder = public_path('branch/logo');

                    if (!file_exists($folder)) {
                        mkdir($folder, 0755, true);
                    }

                    $file->move($folder, $imageName);
                }

                if ($imageName) {
                    $data['Br_Logo'] = url('branch/logo/'.$imageName);
                }
            }

            $branch->update($data);

            return response()->json([
                'success' => true,
                'message' => 'Branch updated successfully',
                'data' => $branch
            ], Response::HTTP_OK);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Failed to update branch',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }


    public function destroy($id)
    {
        try {

            $branch = BranchMaster::find($id);

            if (!$branch) {
                return response()->json([
                    'success' => false,
                    'message' => 'Branch not found'
                ], Response::HTTP_NOT_FOUND);
            }

            $branch->delete();

            return response()->json([
                'success' => true,
                'message' => 'Branch deleted successfully'
            ], Response::HTTP_OK);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Failed to delete branch',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }


    public function restore($id)
    {
        try {

            $branch = BranchMaster::withTrashed()->find($id);

            if (!$branch) {
                return response()->json([
                    'success' => false,
                    'message' => 'Branch not found'
                ], Response::HTTP_NOT_FOUND);
            }

            $branch->restore();

            return response()->json([
                'success' => true,
                'message' => 'Branch restored successfully',
                'data' => $branch
            ], Response::HTTP_OK);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Failed to restore branch',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }


    public function forceDelete($id)
    {
        try {

            $branch = BranchMaster::withTrashed()->find($id);

            if (!$branch) {
                return response()->json([
                    'success' => false,
                    'message' => 'Branch not found'
                ], Response::HTTP_NOT_FOUND);
            }

            $branch->forceDelete();

            return response()->json([
                'success' => true,
                'message' => 'Branch permanently deleted'
            ], Response::HTTP_OK);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Failed to permanently delete',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }


    public function trashed()
    {
        try {

            $data = BranchMaster::onlyTrashed()->get();

            return response()->json([
                'success' => true,
                'message' => 'Deleted branches retrieved',
                'data' => $data
            ], Response::HTTP_OK);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve deleted branches',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
}
