<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Bank;
use App\Models\BankBuyCash;
use App\Models\BankCash;
use App\Models\BankModification;
use App\Models\BankProcess;
use App\Models\BankSafeTransfer;
use App\Models\BankTransfer;
use App\Models\Company;
use App\Models\ExtraSettings;
use App\Models\Safe;
use App\Models\SafeBankTransfer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class BankController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:عرض قائمة البنوك', ['only' => ['index','bank_state']]);
        $this->middleware('permission:اضافة بنك جديد', ['only' => ['create', 'store','edit','update']]);
        $this->middleware('permission:تحويل بين البنوك', ['only' => ['banks_transfer','banks_transfer_store','banks_transfer_destroy']]);
        $this->middleware('permission:سحب وايداع ', ['only' => ['banks_process']]);
        $this->middleware('permission:تحويل من البنوك إلي الخزن', ['only' => ['bank_safe_transfer','bank_safe_transfer_store','bank_safe_transfer_destroy']]);
        $this->middleware('permission:تحويل من الخزن إلي البنوك', ['only' => ['safe_bank_transfer','safe_bank_transfer_store','safe_bank_transfer_destroy']]);
        
    }
    public function index()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $banks = $company->banks;
        return view('client.banks.index', compact('company', 'company_id', 'banks'));
    }

    public function create()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        return view('client.banks.create', compact('company_id', 'company'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'bank_name' => 'required',
            'bank_balance' => 'required',
        ]);
        $data = $request->all();
        $data['balance_start'] = $request->bank_balance ;
        $bank = Bank::create($data);
        return response()->json(['status'=>true,'message'=>'تم إضافة البنك بنجاح']);
    }

    public function edit($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $bank = Bank::findOrFail($id);
        return view('client.banks.edit', compact('bank', 'company_id', 'company'));
    }

    public function update(Request $request)
    {
        $this->validate($request, [
            'bank_name' => 'required',
            'balance_start' => 'required',
            'reason'=>'required'
        ]);
        $input = $request->all();
        $bank = Bank::findOrFail($request->id);
        $balance_before = $bank->balance_start;
        $bank->update($input);
        $balance_after = $request->balance_start;
        BankModification::create([
            'company_id' => $request->company_id,
            'client_id' => Auth::user()->id,
            'bank_id' => $bank->id,
            'reason' => $request->reason,
            'balance_before' => $balance_before,
            'balance_after' => $balance_after,
        ]);
        return response()->json(['status'=>true,'message'=>'تم تحديث البنك بنجاح']);

    }

    public function delete(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $bank = Bank::findOrFail($request->id);
        $bank_opreation_in = BankCash::where('company_id',$company_id)->where('bank_id',$bank->id)->get();
        $bank_opreation_out = BankBuyCash::where('company_id',$company_id)->where('bank_id',$bank->id)->get();
       if($bank_opreation_in->isEmpty() && $bank_opreation_out->isEmpty() ){
       
        $bank->delete();
        return response()->json(['status'=>true,'message'=>'تم حذف البنك بنجاح','sol'=>'']);

       }else{

        return response()->json(['status'=>false,'message'=>'لا يمكن حذف البنك','sol'=>'يرجي تسوية العمليات علي هذا البنك أولا']);

       }
    }

    public function banks_process($id,$type)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $banks = Bank::where('company_id', $company_id)->FindOrFail($id);;
        $banks_process = BankProcess::where('company_id', $company_id)->where('bank_id',$id)->get();
        return view('client.banks.process', compact('banks', 'banks_process', 'company_id', 'company','type','id'));
    }

    public function banks_process_store(Request $request)
    {
        $this->validate($request, [
            'amount' => 'required',
            'reason' => 'required',
            'bank_id' => 'required',
            'process_type' => 'required',
        ]);

        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $banks = Bank::where('company_id', $company_id)->get();
        $bank = Bank::FindOrFail($request->bank_id);
        $balance_before = $bank->bank_balance;
        $amount = $request->amount;
        $process_type = $request->process_type;
        if($process_type == "withdrawal" && $balance_before<$amount){return response()->json(['status'=>false,'message'=>'الرصيد غير كافي ل إجراء عملية السحب']);}
        if ($process_type == "withdrawal") {
            $balance_after = $balance_before - $amount;
        } elseif ($process_type == "deposit") {
            $balance_after = $balance_before + $amount;
        }
        BankProcess::create([
            'company_id' => $request->company_id,
            'client_id' => Auth::user()->id,
            'bank_id' => $request->bank_id,
            'reason' => $request->reason,
            'amount' => $amount,
            'process_type' => $process_type,
            'balance_before' => $balance_before,
            'balance_after' => $balance_after,
        ]);
        $bank->update([
            'bank_balance' => $balance_after,
            'updated_at' => now()
        ]);
      
        return response()->json(['status'=>true,'message'=>'تم تسجيل العملية بنجاح']);
    }

    public function banks_process_destroy(Request $request)
    {
        $process_id = $request->id;
        $process = BankProcess::FindOrFail($process_id);
        $bank = Bank::FindOrFail($process->bank_id);
        $balance_before = $bank->bank_balance;
        $amount = $process->amount;
        $process_type = $process->process_type;
        if ($process_type == "سحب") {
            $balance_after = $balance_before + $amount;
        } elseif ($process_type == "إيداع") {
            $balance_after = $balance_before - $amount;
        }
        $process->delete();
        $bank->update([
            'bank_balance' => $balance_after,
            'updated_at' => now()
        ]);

        return response()->json(['status'=>true,'message'=>'تم حذف العملية بنجاح']);

    }


    public function banks_transfer($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $banks = Bank::where('company_id', $company_id)->where('id',$id)->first();
        $banks_transfer = BankTransfer::where('company_id', $company_id)->orwhere('withdrawal_bank',$id)->orwhere('deposit_bank',$id)->get();
        $otherbanks= Bank::where('company_id', $company_id)->where('id','!=',$id)->get();
        return view('client.banks.transfer', compact('banks', 'banks_transfer', 'company_id', 'company','id','otherbanks'));
    }

    public function banks_transfer_store(Request $request)
    {
        $this->validate($request, [
            'amount' => 'required',
            'reason' => 'required',
            'withdrawal_bank' => 'required',
            'deposit_bank' => 'required',
        ]);
        
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $amount = $request->amount;
        $withdrawal_bank = Bank::FindOrFail($request->withdrawal_bank);
        $deposit_bank = Bank::FindOrFail($request->deposit_bank);
        $balance_before_withdrawal_bank = $withdrawal_bank->bank_balance;
        $balance_before_deposit_bank = $deposit_bank->bank_balance;
        $balance_after_withdrawal_bank = $balance_before_withdrawal_bank - $amount;
        $balance_after_deposit_bank = $balance_before_deposit_bank + $amount;
        if($balance_before_withdrawal_bank<$amount){return response()->json(['status'=>false,'message'=>'رصيد البنك غير كافي لإتمام العملية']);}
        BankTransfer::create([
            'company_id' => $request->company_id,
            'client_id' => Auth::user()->id,
            'withdrawal_bank' => $request->withdrawal_bank,
            'deposit_bank' => $request->deposit_bank,
            'reason' => $request->reason,
            'amount' => $amount,
        ]);
        $withdrawal_bank->update([
            'bank_balance' => $balance_after_withdrawal_bank,
            'updated_at' => now()
        ]);
        $deposit_bank->update([
            'bank_balance' => $balance_after_deposit_bank,
            'updated_at' => now()
        ]);
        return response()->json(['status'=>true,'message'=>'تم تسجيل العملية بنجاح']);

    }

    public function banks_transfer_destroy(Request $request)
    {

        $transfer_id = $request->id;
        $transfer = BankTransfer::FindOrFail($transfer_id);
        $amount = $transfer->amount;
        $withdrawal_bank = Bank::FindOrFail($transfer->withdrawal_bank);
        $deposit_bank = Bank::FindOrFail($transfer->deposit_bank);
        $balance_before_withdrawal_bank = $withdrawal_bank->bank_balance;
        $balance_before_deposit_bank = $deposit_bank->bank_balance;

        $balance_after_withdrawal_bank = $balance_before_withdrawal_bank + $amount;
        $balance_after_deposit_bank = $balance_before_deposit_bank - $amount;

        $transfer->delete();
        $withdrawal_bank->update([
            'bank_balance' => $balance_after_withdrawal_bank,
            'updated_at' => now()
        ]);
        $deposit_bank->update([
            'bank_balance' => $balance_after_deposit_bank,
            'updated_at' => now()
        ]);
        return response()->json(['status'=>true,'message'=>'تم حذف العملية بنجاح']);

    }
    public function bank_safe_transfer($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $banks = Bank::where('company_id',$company_id)->where('id',$id)->first();
        $safes = $company->safes;
        $bank_safe_transfer = BankSafeTransfer::where('company_id', $company_id)
            ->get();
        return view('client.banks.bank_safe_transfer', compact('id','banks', 'bank_safe_transfer','safes', 'company_id', 'company'));
    }

    public function bank_safe_transfer_store(Request $request)
    {
        $this->validate($request, [
            'bank_id' => 'required',
            'safe_id' => 'required',
            'amount' => 'required',
            'reason' => 'required',
        ]);

        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $amount = $request->amount;
        $bank = Bank::FindOrFail($request->bank_id);
        $safe = Safe::FindOrFail($request->safe_id);
        $balance_before_bank = $bank->bank_balance;
        $balance_before_safe = $safe->balance;

        $balance_after_bank = $balance_before_bank - $amount;
        $balance_after_safe = $balance_before_safe + $amount;
        if($balance_before_bank<$amount){return response()->json(['status'=>false,'message'=>'رصيد البنك غير كافي لإتمام العملية']);}

        BankSafeTransfer::create([
            'company_id' => $request->company_id,
            'client_id' => Auth::user()->id,
            'bank_id' => $request->bank_id,
            'safe_id' => $request->safe_id,
            'reason' => $request->reason,
            'amount' => $amount,
        ]);
        $bank->update([
            'bank_balance' => $balance_after_bank,
            'updated_at' => now()
        ]);
        $safe->update([
            'balance' => $balance_after_safe,
            'updated_at' => now()
        ]);
        return response()->json(['status'=>true,'message'=>'تم تسجيل العملية بنجاح']);

    }

    public function bank_safe_transfer_destroy(Request $request)
    {
        $transfer_id = $request->id;
        $transfer = BankSafeTransfer::FindOrFail($transfer_id);
        $amount = $transfer->amount;
        $bank = Bank::FindOrFail($transfer->bank_id);
        $safe = Safe::FindOrFail($transfer->safe_id);
        $balance_before_bank = $bank->bank_balance;
        $balance_before_safe = $safe->balance;

        $balance_after_bank = $balance_before_bank + $amount;
        $balance_after_safe = $balance_before_safe - $amount;

        $transfer->delete();
        $bank->update([
            'bank_balance' => $balance_after_bank,
            'updated_at' => now()
        ]);
        $safe->update([
            'balance' => $balance_after_safe,
            'updated_at' => now()
        ]);
        return response()->json(['status'=>true,'message'=>'تم حذف العملية بنجاح']);

    }


    public function safe_bank_transfer($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $banks = $company->banks;
        $safes = Safe::where('company_id',$company_id)->where('id',$id)->first();
        $safe_bank_transfer = SafeBankTransfer::where('company_id', $company_id)->get();
        return view('client.banks.safe_bank_transfer', compact('banks', 'safe_bank_transfer','safes', 'company_id', 'company'));
    }

    public function safe_bank_transfer_store(Request $request)
    {
        $this->validate($request, [
            'bank_id' => 'required',
            'safe_id' => 'required',
            'amount' => 'required',
            'reason' => 'required',
        ]);

        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $amount = $request->amount;
        $safe = Safe::FindOrFail($request->safe_id);
        $bank = Bank::FindOrFail($request->bank_id);
        $balance_before_safe = $safe->balance;
        $balance_before_bank = $bank->bank_balance;

        $balance_after_safe = $balance_before_safe - $amount;
        $balance_after_bank = $balance_before_bank + $amount;

        SafeBankTransfer::create([
            'company_id' => $request->company_id,
            'client_id' => Auth::user()->id,
            'safe_id' => $request->safe_id,
            'bank_id' => $request->bank_id,
            'reason' => $request->reason,
            'amount' => $amount,
        ]);
        $safe->update([
            'balance' => $balance_after_safe,
            'updated_at' => now()
        ]);
        $bank->update([
            'bank_balance' => $balance_after_bank,
            'updated_at' => now()
        ]);
        return response()->json(['status'=>true,'message'=>'تم حذف العملية بنجاح']);

    }

    public function safe_bank_transfer_destroy(Request $request)
    {
        $transfer_id = $request->id;
        $transfer = SafeBankTransfer::FindOrFail($transfer_id);
        $amount = $transfer->amount;
        $safe = Safe::FindOrFail($transfer->safe_id);
        $bank = Bank::FindOrFail($transfer->bank_id);
        $balance_before_safe = $safe->balance;
        $balance_before_bank = $bank->bank_balance;

        $balance_after_safe = $balance_before_safe + $amount;
        $balance_after_bank = $balance_before_bank - $amount;
        $transfer->delete();
        $safe->update([
            'balance' => $balance_after_safe,
            'updated_at' => now()
        ]);
        $bank->update([
            'bank_balance' => $balance_after_bank,
            'updated_at' => now()
        ]);
        return response()->json(['status'=>true,'message'=>'تم حذف العملية بنجاح']);

    }

    public function bank_state($id) {
        
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $currency = $extra_settings->currency;
        $from_date="";
        $to_date="";

        $bank_id = $id;
        if (empty($from_date) || empty($to_date)) {
            $bank_k = Bank::FindOrFail($bank_id);
            $bank_modifications = BankModification::where('bank_id', $bank_id)->get();
            $bank_processes = BankProcess::where('bank_id', $bank_id)->get();
            $bank_transfers = BankTransfer::where('withdrawal_bank', $bank_id)
                ->orwhere('deposit_bank', $bank_id)
                ->get();
            $bank_safe_transfers = BankSafeTransfer::where('bank_id', $bank_id)->get();
            $safe_bank_transfers = SafeBankTransfer::where('bank_id', $bank_id)->get();

            $bank_cash = BankCash::where('bank_id', $bank_id)->get();
            $bank_buy_cash = BankBuyCash::where('bank_id', $bank_id)->get();
        } else {
            $bank_k = Bank::FindOrFail($bank_id);
            $bank_modifications = BankModification::where('bank_id', $bank_id)
                
                ->get();
            $bank_processes = BankProcess::where('bank_id', $bank_id)
                
                ->get();
            $bank_transfers = BankTransfer::where('withdrawal_bank', $bank_id)
                ->orwhere('deposit_bank', $bank_id)
                ->get();
            $bank_safe_transfers = BankSafeTransfer::where('bank_id', $bank_id)
                ->get();
            $safe_bank_transfers = SafeBankTransfer::where('bank_id', $bank_id)
                ->get();

            $bank_cash = BankCash::where('bank_id', $bank_id)
                ->get();
            $bank_buy_cash = BankBuyCash::where('bank_id', $bank_id)
                ->get();
        }
        $banks = $company->banks;
        return view('client.reports.report15',
            compact('company', 'banks', 'bank_k', 'bank_modifications',
                'bank_processes', 'bank_transfers', 'bank_cash', 'bank_buy_cash',
                'company_id', 'from_date', 'safe_bank_transfers', 'bank_safe_transfers', 'bank_id', 'to_date', 'currency'));
    }
}
