<?php
namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use App\Main;
use App\Sort;
use App\Branch;
use App\Store_Branch;
use App\Store_History;
use App\Payment_Method;
use App\Supplier;
use App\Waste;
use App\Packingmethod;
use App\Physicalcondition;
use App\Driver;
use App\Vehicle;
use App\User;
use App\Customer;
use Carbon\Carbon;
use Auth;
use App\Safe_Account;
use App\Client;
use App\Invoice;
use App\Invoice_Item;
use App\Invoice_Payment;
use App\Cheque;
use App\Bank;
use App\Client_Sheet;
use App\Payment_Voucher;
use App\Employee;
use App\Budget;
use App\Car_Expense;
use App\Car;
use App\Trust;
use App\Safe_History;
use App\Safe_Back;
use App\Notifications;

class PaymentVoucherController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }


public function SendNotification ($admin_name,$action , $pay ,$safe_account,  $general_name){


$onesignalAppId = "a7e5d801-ffac-42aa-8551-e7e6e26380e6";
$onesignalApiKey = "os_v2_app_u7s5qap7vrbkvbkr47toey4a4y5y4l4mh4dev5ejtqbatrgeb6cysaaley7g5x7r33dfyjkjqaaky2ujg6nyl5g6crocufk3dk4leey";

// محتوى الإشعار
$heading = array(
    "en" => $action
);
$content = array(
    "en" => " يطلب $admin_name  $action بقيمة  $pay  من حساب $safe_account الي $general_name "
);

$data = array(
    "screen" => "Notificationstore"
);

// بيانات الإشعار
$fields = array(
    'app_id' => $onesignalAppId,
    'included_segments' => array('All'), // أو تستخدم 'include_player_ids' لمستخدمين محددين
    'headings' => $heading,
    'contents' => $content,
    'data' => $data,
  

);

$fields = json_encode($fields);

$ch = curl_init();
//curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/");
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json; charset=utf-8',
    'Authorization: Basic ' . $onesignalApiKey
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

print_r($response);


}

public function payment_voucher_show(Request $request)
{
    $dateFrom = $request ['from'];
    $dateTo = $request ['to'];
    $branch_id = Auth::user()->branch_id ;
    $payment_vouchers = Payment_Voucher::where("branch_id",$branch_id)
    ->whereDate( 'created_at',">=", $dateFrom)->whereDate('created_at',"<=", $dateTo )
    ->get();
    return view('payment_voucher.show' , 
    ['payment_vouchers' => $payment_vouchers ,'from'=>$dateFrom, 'to'=>$dateTo
     ]);

}

public function payment_voucher_create()
{
    return view('payment_voucher.create' );

}



// general Payment
public function general_payment_voucher_create_get()
{
    $banks = Bank::select('id', 'name')->get();
    $branch_id = Auth::user()->branch_id ;
    $accounts = Safe_Account::with('payment_method')->where('branch_id',$branch_id)->get();
    return view('payment_voucher.general_create_receipt' ,  ['banks' => $banks , "accounts"=>$accounts ]);

}

public function general_payment_voucher_create_post( Request $request)
{    

    $safe_account_ = Safe_Account::where( 'id', $request ['safe_account_id'] )->first();
    
    if ( $safe_account_->balance  < $request ['pay'] ){
        session()->flash('message', 'Can Not Add The payment because No Enough Money! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/general_create" );
    }
    
    $branch_id = Auth::user()->branch_id ;
    $user_id = Auth::user()->id ; // admin_id
    $cheque_or_deposite = $request ['cheque_or_deposite'];
    $general_name = $request ['general_name'];
    $cheque=NULL;
    if ( $cheque_or_deposite ) {
        
        if ( $cheque_or_deposite =="cheque" ){
        $cheque_old = Cheque::where( 'serial', $request ['serial_'] )
                                ->where( 'bank_id', $request ['bank_id'] )
                                ->where( 'date', $request ['date_'] )
                                ->first();
        
        if (!$cheque_old){
            session()->flash('message', 'There is no cheque with this info! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/general_create" );
        }    
        }
        
        $cheque = Cheque::create ( [ 		
            'serial'=> $request ['serial_'] ,
            'bank_id'=> $request ['bank_id'] ,
            'date'=>$request ['date_'],
            'client_id' => $request ['client_id'],
            'invoice_id'=>NULL,
            "branch_id"=>$branch_id,
            "pay"=>$request ['pay'],
            "cheque_or_deposite"=>$cheque_or_deposite=="cheque"?"cheque":"deposite"
            ]);
    }
    
    $payment_voucher = Payment_Voucher::create ( [ 		
        'client_id' => NULL,
        'general_name'=>$request ['general_name'],
        'note1' => $request ['note1'],
        'note2' => $request ['note2'],
        'pay' => $request ['pay'],
        'cheque_id' => $cheque ? $cheque->id : NULL,
        'safe_account_id'=>$request ['safe_account_id'],
        'type'=>"سند صرف عام",
        "branch_id"=>$branch_id,
        "user_id"=>$user_id,
        'approve'=>"Waiting"
    ] );

    if ( $cheque ) {
        DB::table('cheque')
            ->where('id', $cheque->id)
            ->update([ 'payment_voucher_id' => $payment_voucher->id
            ]);
        }

    session()->flash('message', 'New Payment General Voucher Added Successfully');
    session()->flash('type', 'success');
    
    
    //added for notifivation
$pay=$request ['pay'];
$admin_name = Auth::user()->name ;
$branch_name = Auth::user()->branch->name ;
$safe_account_name = $safe_account_->payment_method->name;
$final_name= "". $safe_account_name ." ". $branch_name;
$action ="سند صرف عام";
$notes= " / ". $request ['note1']. " / " . $request ['note2']." ";
$n = Notifications::create ( [  'type'=>$action,'action'=> " يطلب $admin_name  $action بقيمة  $pay  من حساب $final_name الي $general_name "] );
$this->SendNotification ($admin_name, $action , $pay , $final_name,  $general_name.$notes);

//end notifivation

    return redirect ( "/payment_voucher/general_create" );

}


// Employee Payment عمال و موظفين
public function employee_payment_voucher_create_get()
{ 
    $branch_id = Auth::user()->branch_id ;

    $employees = Employee::select('id', 'name')
    ->where('status','=','active')
    ->get();

    $banks = Bank::select('id', 'name')->get();
   
    $accounts = Safe_Account::with('payment_method')->where('branch_id',$branch_id)->get();
    return view('payment_voucher.employee_create_receipt' ,  ['employees'=>$employees,'banks' => $banks , "accounts"=>$accounts ]);

}

public function employee_payment_voucher_create_post( Request $request)
{    
    
    $safe_account_ = Safe_Account::where( 'id', $request ['safe_account_id'] )->first();
    
    if ( $safe_account_->balance  < $request ['pay'] ){
        session()->flash('message', 'Can Not Add The payment because No Enough Money! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/employee_create" );
    }
    
    
    $branch_id = Auth::user()->branch_id ;
    $user_id = Auth::user()->id ; // admin_id
    $cheque_or_deposite = $request ['cheque_or_deposite'];
    $employee_id = $request ['employee_id'];
    $cheque=NULL;
    if ( $cheque_or_deposite ) {
        
        if ( $cheque_or_deposite =="cheque" ){
        $cheque_old = Cheque::where( 'serial', $request ['serial_'] )
                                ->where( 'bank_id', $request ['bank_id'] )
                                ->where( 'date', $request ['date_'] )
                                ->first();
        }
        if (!$cheque_old){
            session()->flash('message', 'There is no cheque with this info! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/employee_create" );
        }
        
        $cheque = Cheque::create ( [ 		
            'serial'=> $request ['serial_'] ,
            'bank_id'=> $request ['bank_id'] ,
            'date'=>$request ['date_'],
            'client_id' => $request ['client_id'],
            'invoice_id'=>NULL,
            "branch_id"=>$branch_id,
            "pay"=>$request ['pay'],
            "cheque_or_deposite"=>$cheque_or_deposite=="cheque"?"cheque":"deposite"
            ]);
    }
    
    $payment_voucher = Payment_Voucher::create ( [ 		
        'client_id' => NULL,
        'general_name'=>NULL,
        'note1' => $request ['note1'],
        'note2' => $request ['note2'],
        'pay' => $request ['pay'],
        'cheque_id' => $cheque ? $cheque->id : NULL,
        'safe_account_id'=>$request ['safe_account_id'],
        'type'=>"سند صرف موظفين",
        'approve'=>"Waiting",
        "branch_id"=>$branch_id,
        "user_id"=>$user_id,
        'employee_id'=>$request ['employee_id']
    ] );


    if ( $cheque ) {
        DB::table('cheque')
            ->where('id', $cheque->id)
            ->update([ 'payment_voucher_id' => $payment_voucher->id
            ]);
        }
    
    session()->flash('message', 'New Payment Employee Voucher Added Successfully');
    session()->flash('type', 'success');
    
    
    
    
//added for notifivation
$pay=$request ['pay'];
$admin_name = Auth::user()->name ;
$branch_name = Auth::user()->branch->name ;
$safe_account_name = $safe_account_->payment_method->name;
$final_name= "". $safe_account_name ." ". $branch_name;
$action ="سند صرف موظفين";
$emplloyee = Employee::where( 'id', $request ['employee_id'] )->first();
$general_name = $emplloyee->name . " / ". $request ['note1']. " / " . $request ['note2'];
$n = Notifications::create ( [  'type'=> $action ,'action'=> " يطلب $admin_name  $action بقيمة  $pay  من حساب $final_name الي $general_name "] );
$this->SendNotification ($admin_name,$action , $pay , $final_name,  $general_name );

//end notifivation
    
    
    return redirect ( "/payment_voucher/employee_create" );

}

// budget سند صرف مربوط بميزانية

public function budget_payment_voucher_create_get()
{
    $branch_id = Auth::user()->branch_id ;
    $banks = Bank::select('id', 'name')->get();
    $accounts = Safe_Account::with('payment_method')->where('branch_id',$branch_id)->get();
    $budgets = Budget::select('id', 'name')->where('branch_id',$branch_id)->get();
    return view('payment_voucher.budget_create_receipt' ,  ['budgets'=>$budgets,'banks' => $banks , "accounts"=>$accounts ]);

}

public function budget_payment_voucher_create_post( Request $request)
{    
     $safe_account_ = Safe_Account::where( 'id', $request ['safe_account_id'] )->first();
    
    if ( $safe_account_->balance  < $request ['pay'] ){
        session()->flash('message', 'Can Not Add The payment because No Enough Money! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/budget_create" );
    }
    
    $branch_id = Auth::user()->branch_id ;
    $user_id = Auth::user()->id ; // admin_id
    $cheque_or_deposite = $request ['cheque_or_deposite'];
    $general_name = $request ['general_name'];
    $budget_id = $request ['budget_id'];
    $budget = Budget::where('id',$budget_id)->first();
    $pay = $request ['pay'];

    $current_month_name =  date('F Y');
    $first_day_of_month = date('Y-m-01');   
    $last_day_of_month =  date("Y-m-t", strtotime($first_day_of_month));
    $total_consume = Payment_Voucher::where('budget_id' ,$budget_id)->where('approve',"approved")
    ->whereDate('created_at','>=',$first_day_of_month)
    ->whereDate('created_at','<=',$last_day_of_month)
    ->sum('pay');
    $budget_avilable = $budget->amount +  $budget->temp_amount - $total_consume; 
    


    if ( $pay  > $budget_avilable  ){
    session()->flash('message', "Can not Add The Budget Payment , Limit Exceed The Budget Aviliable $budget_avilable ");
    session()->flash('type', 'danger');
    return redirect ( "/payment_voucher/budget_create" );
    }

    $cheque=NULL;
    if ( $cheque_or_deposite ) {
        
        if ( $cheque_or_deposite =="cheque" ){
        $cheque_old = Cheque::where( 'serial', $request ['serial_'] )
                                ->where( 'bank_id', $request ['bank_id'] )
                                ->where( 'date', $request ['date_'] )
                                ->first();
        }
        if (!$cheque_old){
            session()->flash('message', 'There is no cheque with this info! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/budget_create" );
        }
        
        $cheque = Cheque::create ( [ 		
            'serial'=> $request ['serial_'] ,
            'bank_id'=> $request ['bank_id'] ,
            'date'=>$request ['date_'],
            'client_id' => $request ['client_id'],
            'invoice_id'=>NULL,
            "pay"=>$request ['pay'],
            "branch_id"=>$branch_id,
            "cheque_or_deposite"=>$cheque_or_deposite=="cheque"?"cheque":"deposite"
            ]);
    }
    
    $payment_voucher = Payment_Voucher::create ( [ 		
        'client_id' => NULL,
        'general_name'=>$request ['general_name'],
        'note1' => NULL,
        'note2' => $request ['note2'],
        'pay' => $request ['pay'],
        'cheque_id' => $cheque ? $cheque->id : NULL,
        'safe_account_id'=>$request ['safe_account_id'],
        'type'=>"سند صرف ميزانية",
        'approve'=>"Waiting",
        'employee_id'=>NULL,
        "branch_id"=>$branch_id,
        "user_id"=>$user_id,
        'budget_id'=>$request ['budget_id']
    ] );


    // ربط الشيك بسند الصرف المربوط بميزانية و لأن خانة العميل حرة
    if ( $cheque ) {
    DB::table('cheque')
        ->where('id', $cheque->id)
        ->update([ 'payment_voucher_id' => $payment_voucher->id
        ]);
    }

    session()->flash('message', 'New Payment Budget Voucher Added Successfully');
    session()->flash('type', 'success');
    
    
    
    
    
    //added for notifivation
$pay=$request ['pay'];
$admin_name = Auth::user()->name ;
$branch_name = Auth::user()->branch->name ;
$safe_account_name = $safe_account_->payment_method->name;
$final_name= "". $safe_account_name ." ". $branch_name;
$action ="سند صرف ميزانية";
$notes = " / ".  $request ['note2'];
$n = Notifications::create ( [  'type'=> $action ,'action'=> " يطلب $admin_name  $action بقيمة  $pay  من حساب $final_name الي $general_name "] );
$this->SendNotification ($admin_name,$action , $pay , $final_name,  $general_name.$notes );

//end notifivation


    return redirect ( "/payment_voucher/budget_create" );

}




// Car & Transport نقل و سيارات 
public function car_payment_voucher_create_get()
{
    $branch_id = Auth::user()->branch_id ;
    $cars = Car::select('id', 'num')->get();
    $car_expenses = Car_Expense::select('id', 'name')->get();
    $banks = Bank::select('id', 'name')->get();
    $accounts = Safe_Account::with('payment_method')->where('branch_id',$branch_id)->get();
    return view('payment_voucher.car_create_receipt' ,  ['banks' => $banks , "accounts"=>$accounts, "cars"=>$cars, "car_expenses"=>$car_expenses  ]);

}

public function car_payment_voucher_create_post( Request $request)
{    
    
     $safe_account_ = Safe_Account::where( 'id', $request ['safe_account_id'] )->first();
    
    if ( $safe_account_->balance  < $request ['pay'] ){
        session()->flash('message', 'Can Not Add The payment because No Enough Money! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/car_create" );
    }
    
    $branch_id = Auth::user()->branch_id ;
    $user_id = Auth::user()->id ; // admin_id
    $cheque_or_deposite = $request ['cheque_or_deposite'];
    
    $cheque=NULL;
    


    if ( $cheque_or_deposite ) {
        
        if ( $cheque_or_deposite =="cheque" ){
            $cheque_old = Cheque::where( 'serial', $request ['serial_'] )
                                ->where( 'bank_id', $request ['bank_id'] )
                                ->where( 'date', $request ['date_'] )
                                ->first();
        
        if (!$cheque_old){
            session()->flash('message', 'There is no cheque with this info! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/car_create" );
        }
        }
        $cheque = Cheque::create ( [ 		
            'serial'=> $request ['serial_'] ,
            'bank_id'=> $request ['bank_id'] ,
            'date'=>$request ['date_'],
            'client_id' => $request ['client_id'],
            'invoice_id'=>NULL,
            "pay"=>$request ['pay'],
            "branch_id"=>$branch_id,
            "cheque_or_deposite"=>$cheque_or_deposite=="cheque"?"cheque":"deposite"
            ]);
    }
    
    $payment_voucher = Payment_Voucher::create ( [ 		
        'client_id' => NULL,
        'general_name'=>$request ['general_name'],
        'note1' => NULL,
        'note2' => $request ['note2'],
        'pay' => $request ['pay'],
        'cheque_id' => $cheque ? $cheque->id : NULL,
        'safe_account_id'=>$request ['safe_account_id'],
        'type'=>"سند صرف سيارات",
        'approve'=>"Waiting",
        'employee_id'=>NULL,
        "branch_id"=>$branch_id,
        "user_id"=>$user_id,
        'car_expense_id'=>$request ['car_expense_id'],
        'car_id'=> $request ['car_id']
    ] );


    if ( $cheque ) {
        DB::table('cheque')
            ->where('id', $cheque->id)
            ->update([ 'payment_voucher_id' => $payment_voucher->id
            ]);
        }
    
    session()->flash('message', 'New Payment Car Voucher Added Successfully');
    session()->flash('type', 'success');
    
    
    
        //added for notifivation
$pay=$request ['pay'];
$admin_name = Auth::user()->name ;
$branch_name = Auth::user()->branch->name ;
$safe_account_name = $safe_account_->payment_method->name;
$final_name= "". $safe_account_name ." ". $branch_name;
$action ="سند صرف سيارات";
$general_name = $request ['general_name'];
$notes = " / ".  $request ['note2'];
$n = Notifications::create ( [  'type'=> $action ,'action'=> " يطلب $admin_name  $action بقيمة  $pay  من حساب $final_name الي $general_name "] );
$this->SendNotification ($admin_name,$action , $pay , $final_name,  $general_name.$notes );

//end notifivation


    return redirect ( "/payment_voucher/car_create" );

}


///////////////////////////////////////////////////////////////////////////////////////

// Trust - عهد غير مربوطة بمبغ 
public function not_tie_trust_payment_voucher_create_get()
{
    
    
    $branch_id = Auth::user()->branch_id ;

   

    $trusts  = Trust::select('id', 'name')->where('type','عهدة غير مربوطة بمبلغ')->where("status","!=","END")->get();
    $car_expenses = Car_Expense::select('id', 'name')->get();
    $banks = Bank::select('id', 'name')->get();
    $accounts = Safe_Account::with('payment_method')->where('branch_id',$branch_id)->get();
    return view('payment_voucher.not_tie_trust_create_receipt' ,  ['banks' => $banks , "accounts"=>$accounts ,  "trusts"=>$trusts ]);

}
// Trust - عهد غير مربوطة بمبغ 
public function not_tie_trust_payment_voucher_create_post( Request $request)
{    
    
    $safe_account_ = Safe_Account::where( 'id', $request ['safe_account_id'] )->first();
    
    if ( $safe_account_->balance  < $request ['pay'] ){
        session()->flash('message', 'Can Not Add The payment because No Enough Money! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/not_tie_trust_create" );
    }
    
    
    $branch_id = Auth::user()->branch_id ;
    $user_id = Auth::user()->id ; // admin_id
    $cheque_or_deposite = $request ['cheque_or_deposite'];
   
    $trust_id = $request ['trust_id'];
    
    $cheque=NULL;
    if ( $cheque_or_deposite ) {
        
        if ( $cheque_or_deposite =="cheque" ){
        $cheque_old = Cheque::where( 'serial', $request ['serial_'] )
                                ->where( 'bank_id', $request ['bank_id'] )
                                ->where( 'date', $request ['date_'] )
                                ->first();
        }
        if (!$cheque_old){
            session()->flash('message', 'There is no cheque with this info! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/not_tie_trust_create" );
        }
        
        $cheque = Cheque::create ( [ 		
            'serial'=> $request ['serial_'] ,
            'bank_id'=> $request ['bank_id'] ,
            'date'=>$request ['date_'],
            'client_id' => NULL,
            'invoice_id'=>NULL,
            "pay"=>$request ['pay'],
            "branch_id"=>$branch_id,
            "cheque_or_deposite"=>$cheque_or_deposite=="cheque"?"cheque":"deposite"
            ]);
    }
    
    $payment_voucher = Payment_Voucher::create ( [ 		
        'client_id' => NULL,
        'general_name'=>$request ['general_name'],
        'note1' => NULL,  
        'note2' => $request ['note2'],
        'pay' => $request ['pay'],
        'cheque_id' => $cheque ? $cheque->id : NULL,
        'safe_account_id'=>$request ['safe_account_id'],
        'type'=>"سند صرف عهدة غير مربوطة بمبلغ",
        'approve'=>"Waiting",
        "branch_id"=>$branch_id,
        "user_id"=>$user_id,
        'trust_id'=>$request ['trust_id']
    ] );


    if ( $cheque ) {
        DB::table('cheque')
            ->where('id', $cheque->id)
            ->update([ 'payment_voucher_id' => $payment_voucher->id
            ]);
        }    
    session()->flash('message', 'New Payment Trust Voucher Added Successfully');
    session()->flash('type', 'success');
    
    
     //added for notifivation
$pay=$request ['pay'];
$admin_name = Auth::user()->name ;
$branch_name = Auth::user()->branch->name ;
$safe_account_name = $safe_account_->payment_method->name;
$final_name= "". $safe_account_name ." ". $branch_name;
$action ="  صرف عهدة غير مربوطة بمبلغ ";
$general_name = $request ['general_name'];
$n = Notifications::create ( [  'type'=> $action ,'action'=> " يطلب $admin_name  $action بقيمة  $pay  من حساب $final_name الي $general_name "] );
$this->SendNotification ($admin_name,$action , $pay , $final_name,  $general_name );

//end notifivation

    return redirect ( "/payment_voucher/not_tie_trust_create" );

}



// Trust - عهدة مربوطة بمبلغ 
public function tie_trust_payment_voucher_create_get()
{
    $branch_id = Auth::user()->branch_id ;
    
   

    $trusts  = Trust::select('id', 'name')->where('type','عهدة مربوطة بمبلغ')->where('approve','Approved')->where("status","!=","END")->get();
    $car_expenses = Car_Expense::select('id', 'name')->get();
    $banks = Bank::select('id', 'name')->get();
    $accounts = Safe_Account::with('payment_method')->where('branch_id',$branch_id)->get();
    return view('payment_voucher.tie_trust_create_receipt' ,  ['banks' => $banks , "accounts"=>$accounts , "trusts"=>$trusts ]);

}
// Trust - عهدة مربوطة بمبلغ 
public function tie_trust_payment_voucher_create_post( Request $request)
{    
    
   
    $safe_account_ = Safe_Account::where( 'id', $request ['safe_account_id'] )->first();
    
    if ( $safe_account_->balance  < $request ['pay'] ){
        session()->flash('message', 'Can Not Add The payment because No Enough Money! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/tie_trust_create" );
    }
    
    
    $branch_id = Auth::user()->branch_id ;
    $user_id = Auth::user()->id ; // admin_id
    $cheque_or_deposite = $request ['cheque_or_deposite'];
    
    $trust_id = $request ['trust_id'];
    $trust = Trust::where('id',$trust_id)->first();
    $pay = $request ['pay'];

    $total_consume = Payment_Voucher::where('trust_id' ,$trust_id)->where('approve',"approved")
    ->sum('pay');
    $total_pay_back = Safe_Back::where('trust_id' ,$trust_id)->sum('pay_back');
    $trust_avilable = $trust->amount  - $total_consume -  $total_pay_back; 
    


    if ( $pay  > $trust_avilable  ){
    session()->flash('message', "Can not Add The Trust Payment , Limit Exceed The Trust Aviliable $trust_avilable ");
    session()->flash('type', 'danger');
    return redirect ( "/payment_voucher/tie_trust_create" );
    }


    $cheque=NULL;
    if ( $cheque_or_deposite ) {
        
        if ( $cheque_or_deposite =="cheque" ){
        $cheque_old = Cheque::where( 'serial', $request ['serial_'] )
                                ->where( 'bank_id', $request ['bank_id'] )
                                ->where( 'date', $request ['date_'] )
                                ->first();
        }
        if (!$cheque_old){
            session()->flash('message', 'There is no cheque with this info! ');
        session()->flash('type', 'danger');
        return redirect ( "/payment_voucher/tie_trust_create" );
        }
        
        $cheque = Cheque::create ( [ 		
            'serial'=> $request ['serial_'] ,
            'bank_id'=> $request ['bank_id'] ,
            'date'=>$request ['date_'],
            'client_id' => NULL,
            'invoice_id'=>NULL,
            "pay"=>$request ['pay'],
            "branch_id"=>$branch_id,
            "cheque_or_deposite"=>$cheque_or_deposite=="cheque"?"cheque":"deposite"
            ]);
    }
    
    $payment_voucher = Payment_Voucher::create ( [ 		
        'client_id' => NULL,
        'general_name'=>$request ['general_name'],
        'note1' => NULL,  
        'note2' => $request ['note2'],
        'pay' => $request ['pay'],
        'cheque_id' => $cheque ? $cheque->id : NULL,
        'safe_account_id'=>$request ['safe_account_id'],
        'type'=>"سند صرف عهدة مربوطة بمبلغ",
        'approve'=>"Approved",
        "branch_id"=>$branch_id,
        "user_id"=>$user_id,
        'trust_id'=>$request ['trust_id']
    ] );


    if ( $cheque ) {
        DB::table('cheque')
            ->where('id', $cheque->id)
            ->update([ 'payment_voucher_id' => $payment_voucher->id
            ]);
        }    

        $safe_account_id = $request ['safe_account_id'] ;
        $safe_account = Safe_Account::where( 'id', $safe_account_id )->first();
        $pay = $request ['pay'];

        
            
            
             Safe_History::insert ( 
            [ 	'balance_before' => $safe_account->balance,
                'user_id' => Auth::user()->id,
                'safe_account_id'=>$safe_account_id,
                'payment_voucher_id' => $payment_voucher->id,
                'movement_type'=> "منصرف",
                "payment_method_id"=>$safe_account->payment_method_id,
                "outcome"=>$pay,
                'balance_after' =>  $safe_account->balance - $pay
            ]);
            
            
    
            // increase  safe account 
            DB::table('safe_accounts')
            ->where('id', $safe_account_id)
            ->update([ 'balance' => DB::raw("balance-$pay"),
                    'updated_at' => Carbon::now()
            ]);


    session()->flash('message', 'New Payment Trust Voucher Added Successfully');
    session()->flash('type', 'success');
    
     //added for notifivation
$pay=$request ['pay'];
$admin_name = Auth::user()->name ;
$branch_name = Auth::user()->branch->name ;
$safe_account_name = $safe_account_->payment_method->name;
$final_name= "". $safe_account_name ." ". $branch_name;
$action =" سند صرف عهدة مربوطة بمبلغ ";
$general_name = $request ['general_name'];
$n = Notifications::create ( [  'type'=> $action ,'action'=> " يطلب $admin_name  $action بقيمة  $pay  من حساب $final_name الي $general_name "] );
$this->SendNotification ($admin_name,$action , $pay , $final_name,  $general_name );

//end notifivation
    return redirect ( "/payment_voucher/tie_trust_create" );

}




public function payment_voucher_edit_get($payment_voucher_id)
{
    $payment_voucher = Payment_Voucher::where('id',$payment_voucher_id)->first();
    return view('payment_voucher.edit' ,  ['payment_voucher' => $payment_voucher  ]);  
}

public function payment_voucher_edit_post( Request $request)
{    
    $branch_id = Auth::user()->branch_id ;
    $user_id = Auth::user()->id ; // admin_id

    $fields = [];
    $payment_voucher_id = $request ['payment_voucher_id'];
    $general_name = $request ['general_name'];
    $note1 = $request ['note1'];
    $note2 = $request ['note2'];
    
    if ($general_name ){
        $fields['general_name'] = $general_name;
    }
    if ($note1 ){
        $fields['note1'] = $note1;
    }
    if ($note2 ){
        $fields['note2'] = $note2;
    }
    

    Payment_Voucher::where('id', $payment_voucher_id)->update($fields);

    session()->flash('message', ' Payment Voucher Updated Successfully');
    session()->flash('type', 'success');


    return redirect ( "/payment_voucher/edit/$payment_voucher_id" );

}




public function details ( $payment_voucher_id ){
    $payment_voucher = Payment_Voucher::where('id',$payment_voucher_id)->first();
    return view('payment_voucher.print' ,  ['payment_voucher' => $payment_voucher  ]);  
}



}
