<?php

namespace App\Http\Controllers;

use App\DataTables\TransferDataTable;
use App\Models\Account;
use App\Models\Transaction;
use App\Models\Transfer;
use App\Models\Installment;
use App\Notifications\TransferNotif;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\installmentExport;



class TransferController extends Controller
{

    //
    public function __construct()
    {
        $this->middleware('permission:show_transfer', ['only' => ['transfers.index']]);
        $this->middleware('permission:add_transfer', ['only' => ['transfers.create', 'transfers.store']]);
        
    }
    private $transfer;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(TransferDataTable $dataTable)
    {
       $user=auth()->user();
       if(!$user->can('show_transfer')){
          abort(401,'you cant see');
       }
       else{
        return $dataTable->render('transfers.index');
       }

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $account = Account::findOrFail($request->account_id);
         
      
        $this->validate($request, [
            'amount' => 'required|numeric',
            'status' => 'required|string',
            'paid_at' => 'required|date',
            'number' => 'required|string|max:191|min:3',
        ]);
        
        $transactions_pennding=Transaction::where('account_id',$request->account_id)->pluck('status')->toarray();

        if(in_array('pending',$transactions_pennding))
        {
           return  response()->json(['errors' => 'your exist account pending'], 422);


        }
        else{
            DB::transaction(function () use ($request, $account) {
                $transaction = Transaction::create([
                    'account_id' => $account->id,
                    'amount' => $request->amount,
                    'status' => $request->status,
                    'paid_at' => $request->paid_at,
                    'currency_code' => $account->currency_code,
                    'exchange_rate' => config('money.' . $account->currency_code . '.rate'),
                    'type' => Transaction::TYPE_INCOME,
                    'category' => Transaction::CATEGORY_TRANSFER
                ]);
    
                $this->transfer = Transfer::create([
                    'transaction_id' => $transaction->id,
                    'number' => $request->number
                ]);
    
            });
    
            $account->owner->notify(new TransferNotif($this->transfer));
    
            return $this->transfer;
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Transfer  $transfer
     * @return \Illuminate\Http\Response
     */
    public function show(Transfer $transfer)
    {
        return [
            'id'=>$transfer->id,
            'status' => $transfer->transaction->status,
            'number' => $transfer->number
        ];
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Transfer  $transfer
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Transfer $transfer)
    {
        $this->validate($request,[
            'status'=>'required|string',
            'number'=>'nullable|string|max:191|min:5',
        ]);

        $transfer->update([
            'number'=>$request->number
        ]);
        $transfer->transaction->status = $request->status;
        $transfer->transaction->save();
        return $transfer;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Transfer  $transfer
     * @return \Illuminate\Http\Response
     */
    public function destroy(Transfer $transfer)
    {
      
      $user=auth()->user();
        if(!$user->can('delete_transfer')){
           
          abort(401,'you cant delete');
       }
       else{
           return DB::transaction(function () use ($transfer) {
            $account = $transfer->transaction->account;
            $account->balance -= $transfer->transaction->amount;
            $transfer->transaction->delete();
            $transfer->delete();
            $account->save();
        });
         }
           
     }
     public function installmentStore(Request $request){
         
        $transfer=Transfer::find($request->transfer_id);
        $installment=Installment::where('transfer_id',$transfer->id)->get();

        $transfer_amount= $transfer->transaction->amount;
        $transfer_amount=$transfer_amount/100;
        $installment_sum=  $installment->sum('amount');
        

       $sum= $request->installments +$installment_sum;


        if((integer)$request->installments > $transfer_amount || (integer) $installment_sum >$transfer_amount ||$sum >$transfer_amount ){
        
            return back()->with('status','payment is greater than amoumt.');
    
        }
      
     
        if($installment_sum == $transfer_amount||$sum ==$transfer_amount){
            
            $transfer->transaction()->update(['status'=>'success']);
            
            
        }
        if($sum ==$transfer_amount){
            Installment::create([
                'amount'=>$request->installments,
                'transfer_id'=>$transfer->id,
                'number'=>$request->number
                ]);
        }
  
        
     else{
            Installment::create([
                'amount'=>$request->installments,
                'transfer_id'=>$transfer->id,
                'number'=>$request->number
                ]);
         }
      return back();
     }
          public function installmentExport() 
    {
        $name = auth()->user()->name;
        return Excel::download(new installmentExport, $name.'.xlsx');
    }
}
