<?php

namespace App\Http\Controllers;

use App\Models\BranchModel;
use App\Models\CompanyModel;
use App\Models\StandardPaperSizeModel;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;


class BranchController extends Controller
{
    public function index()
    {
        $companies = CompanyModel::all();
        $branches = BranchModel::orderBy('id', 'desc')->get();
        return view('branch.index', compact('companies', 'branches'));
    }
    public function add()
    {
        $companies = CompanyModel::all();
        $users = User::where('user_flg', 'A')->get();
        $paperSize = StandardPaperSizeModel::where('oprntl_flag', 'A')->get();
        return view('branch.add', compact('companies', 'users', 'paperSize'));
    }
    public function store(Request $request)
    {

        DB::beginTransaction();
        try {
            // Handle file upload
            $logoPath = null;
            if ($request->hasFile('logo')) {
                $logoPath = storeFile($request->logo, 'logo');
            }

            $company = CompanyModel::findOrFail($request->company);
            $sendInvoice = $request->boolean('send_invoice') ? 'A' : 'I';

            $branch = BranchModel::create([
                'prefix' => $request->prefix,
                'non_gst_prefix' => $request->non_gst_prefix,
                'company_id' => $request->company,
                'company_name' => $company->name,
                'logo' => $logoPath,
                'name' => $request->name,
                'phone' => $request->contact_number,
                'email' => $request->email,
                'address' => $request->address,
                'whatsapp_config' => $sendInvoice,
                'paper_size' => $request->paper_size,
                'gst_no' => $request->gst_no,
                'loyalty_config' => $request->loyalty_point == 1 ? 'A' : 'I',
                'loyalty_amount' => $request->loyalty_amount,
                'declaration' => $request->declaration,
                'point_redemption' => $request->point_redemption,
                'note_flag' => $request->note == 1 ? 'A' : 'I',
                'terms_flag' => $request->term == 1 ? 'A' : 'I',
                'inv_desc_flag' => $request->description == 1 ? 'A' : 'I',
                'price_tax_flag' => $request->price_tax == 1 ? 'A' : 'I',
                'signature_flag' => $request->signature == 1 ? 'A' : 'I',
                'avl_qty_flag' => $request->avl_qty == 1 ? 'A' : 'I',
                'native_name_flag' => $request->native_name == 1 ? 'A' : 'I',
                'is_header' => $request->is_header == 1 ? 'A' : 'I',
                'non_gst' => $request->non_gst == 1 ? 'A' : 'I',
                'whatsapp_template' => $request->whatsapp_template,
            ]);

            if ($request->user_id) {
                DB::table('branch_user')->insert([
                    'user_id' => $request->user_id,
                    'branch_id' => $branch->id,
                ]);
            }

            $users = User::whereIn('user_flg', ['C', 'SU'])->where('active_status', 'A')->get();
            $data = [];
            foreach ($users as $user) {
                $data[] = [
                    'user_id' => $user->id,
                    'branch_id' => $branch->id,
                ];
            }

            DB::table('branch_user')->insert($data);
            DB::commit();

            return redirect()->route('branch-index')
                ->with('success', 'Branch added successfully!');

        } catch (\Exception $e) {
            DB::rollBack();
            logger()->error('Branch creation failed: ' . $e->getMessage());

            return back()->withInput()
                ->with('error', 'Something went wrong! Please try again');
        }
    }
    public function edit($id)
    {
        $branch = BranchModel::findOrFail($id);
        $companies = CompanyModel::all();
        $users = User::where('user_flg', 'A')->get();

        $branch_user = DB::table('branch_user')->where('branch_id', $branch->id)->get();

        $user_ids = $branch_user->pluck('user_id');

        $user_id = $user_ids->isNotEmpty()
            ? User::whereIn('id', $user_ids)
                ->where('user_flg', 'A')
                ->pluck('id')->first()
            : null;

        $paperSize = StandardPaperSizeModel::where('oprntl_flag', 'A')->get();

        // dd($branch);
        return view('branch.edit', compact('companies', 'users', 'paperSize', 'branch', 'user_id'));
    }
    public function update(Request $request)
    {
        $validated = $request->validate([
            'company' => 'required|exists:company,id',
            'prefix' => 'required|string|max:10',
            'name' => 'required|string|max:255',
            'gst_no' => 'required|string|max:50',
            'contact_number' => 'nullable|string|max:20',
            'email' => 'required|email|max:255',
            'address' => 'nullable|string|max:255',
            'user_id' => 'nullable|exists:users,id',
            'paper_size' => 'nullable|exists:standard_paper_size,id',
            'send_invoice' => 'nullable|in:A,I',
            'loyalty_amount' => 'nullable',
        ]);

        DB::beginTransaction();
        try {
            $branch = BranchModel::findOrFail($request->branch_id);

            // Handle file upload
            if ($request->hasFile('logo')) {
                $logoPath = storeFile($request->logo, 'logo');
                $logo = $logoPath;
            } else {
                $logo = $branch->logo;
            }

            // Get company name
            $companyName = CompanyModel::where('id', $validated['company'])->value('name');

            // Update branch
            $branch->update([
                'prefix' => $validated['prefix'],
                'non_gst_prefix' => $request->non_gst_prefix,
                'company_id' => $validated['company'],
                'company_name' => $companyName,
                'logo' => $logo,
                'name' => $validated['name'],
                'phone' => $validated['contact_number'],
                'email' => $validated['email'],
                'address' => $validated['address'],
                'whatsapp_config' => $request->has('send_invoice') ? 'A' : 'I',
                'paper_size' => $validated['paper_size'],
                'gst_no' => $validated['gst_no'],
                'loyalty_config' => $request->has('loyalty_point') ? 'A' : 'I',
                'loyalty_amount' => $validated['loyalty_amount'],
                'declaration' => $request->declaration,
                'point_redemption' => $request->point_redemption,
                'note_flag' => $request->note == 1 ? 'A' : 'I',
                'terms_flag' => $request->term == 1 ? 'A' : 'I',
                'inv_desc_flag' => $request->description == 1 ? 'A' : 'I',
                'price_tax_flag' => $request->price_tax == 1 ? 'A' : 'I',
                'signature_flag' => $request->signature == 1 ? 'A' : 'I',
                'avl_qty_flag' => $request->avl_qty == 1 ? 'A' : 'I',
                'native_name_flag' => $request->native_name == 1 ? 'A' : 'I',
                'is_header' => $request->is_header == 1 ? 'A' : 'I',
                'non_gst' => $request->non_gst == 1 ? 'A' : 'I',
                'whatsapp_template' => $request->whatsapp_template,
            ]);

            // Update or create branch_user relationship
            $exist = DB::table('branch_user')->where('branch_id', $request->branch_id)->where('user_id', $request->user_id)->exists();
            if ($exist) {
                DB::table('branch_user')->where('branch_id', $request->branch_id)->where('user_id', $request->user_id)->update(
                    [
                        'branch_id' => $branch->id,
                        'user_id' => $request->user_id
                    ]
                );
            } else {
                DB::table('branch_user')->insert([
                    'branch_id' => $branch->id,
                    'user_id' => $request->user_id
                ]);
            }

            DB::commit();

            return redirect()->route('branch-index')
                ->with('success', 'Branch updated successfully!');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Branch Edit' . $e);
            return back()->with('error', 'Something went wrong! Please try again');
        }

    }

    public function delete($id)
    {
        $branch = BranchModel::findOrFail($id);

        if ($branch->logo) {
            Storage::delete($branch->logo);
        }
        DB::table('branch_user')->where('branch_id', $branch->id)->delete();
        $branch->delete();

        return redirect()->route('branch-index')
            ->with('success', 'Branch deleted successfully!');
    }

}
