<?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\Receipt;
use App\Safe_History;
use App\Notifications;

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

public function SendNotification ( $noti){

$action ="تنبيه تحصيل بدون فاتورة";


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

// محتوى الإشعار
$heading = array(
    "en" => $action
);
$content = array(
    "en" => " $noti "
);

$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 receipt_show()
{
    $branch_id = Auth::user()->branch_id ;
    $receipts = Receipt::where('branch_id', $branch_id )->orderBy('id', 'desc')->paginate(1000);
    return view('voucher.show_receipts' , ['receipts' => $receipts]);

}


public function receipt_create_get()
{
    $branch_id = Auth::user()->branch_id ;
    $clients = Client::select('id', 'name')->where('branch_id',$branch_id)->get();
    $banks = Bank::select('id', 'name')->get();
    
    
    $accounts = Safe_Account::with('payment_method')->where('branch_id',$branch_id)->get();

    return view('voucher.create_receipt' , ['clients' => $clients, 'banks' => $banks , "accounts"=>$accounts ]);

}




public function receipt_create_post( Request $request)
{
    $branch_id = Auth::user()->branch_id ;
    $cheque_or_deposite = $request ['cheque_or_deposite'];

 
    $cheque=NULL;
    if ( $cheque_or_deposite ) {
        $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"
            ]);
    }
    
    // سند القبض
    $receipt = Receipt::create ( [ 		
        'client_id' => $request ['client_id'],
        'note1' => $request ['note1'],
        'note2' => $request ['note2'],
        'pay' => $request ['pay'],
        'cheque_id' => $cheque ? $cheque->id : NULL,
        "branch_id"=>$branch_id,
        'safe_account_id'=>$request ['safe_account_id']
    ] );

    // حساب العميل 
    Client_Sheet::insert ( 
        [ 		
            'leeh' => $request ['pay'],
            'aleeh' => 0 ,
            'client_id' => $request ['client_id'],
            'invoice_id'  => NULL,
            'receipt_id'  => $receipt->id
        ]);


    // safe history
        $safe_account = Safe_Account::where( 'id', $request ['safe_account_id'] )->first(); 
        
        Safe_History::insert ( 
            [ 	'balance_before' => $safe_account->balance,
                'descreption' => " $receipt->note1  -  $receipt->note2",
                'receipt_id'  => $receipt->id,
                'client_id'=>$request ['client_id'],
                'user_id' => Auth::user()->id,
                'safe_account_id'=>$safe_account->id,
                'movement_type'=> "وارد",
                "payment_method_id"=>$safe_account->payment_method_id,
                "income"=>$receipt->pay,
                'balance_after' =>  $safe_account->balance + $receipt->pay ,
            ]);
    
       
        // increase  safe account 
        DB::table('safe_accounts')
        ->where('id', $receipt->safe_account_id)
        ->update([ 'balance' => DB::raw("balance+$receipt->pay"),
                'updated_at' => Carbon::now()
        ]);
    
    

    //added for notifivation
$pay=$request ['pay'];
$admin_name = Auth::user()->name ;
$branch_name = Auth::user()->branch->name ;
$receipt_id = $receipt->id;
$client = Client::where( 'id', $request ['client_id'] )->first(); 
$client_name = $client->name;
$safe_account_name = $safe_account->payment_method->name;
$final_name= "". $safe_account_name ." ". $branch_name;
$action ="تنبيه تحصيل بدون فاتورة";
$n = Notifications::create ( [  'type'=>$action,'action'=> " قام المستخدم $admin_name بتحصيل مبلغ $pay جنيه من العميل $client_name دون اصدار فاتورة بموجب سند قبض $receipt_id "] );
$this->SendNotification ( "قام المستخدم $admin_name بتحصيل مبلغ $pay جنيه من العميل $client_name دون اصدار فاتورة بموجب سند قبض $receipt_id" );

//end notifivation


    session()->flash('message', 'New Recipt Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/receipt/create" );

}



public function print ( $voucher_id ){
    $voucher = Receipt::where('id',$voucher_id)->first();
    return view('voucher.print' ,  ['voucher' => $voucher  ]);  
}

public function receipt_edit_get($voucher_id)
{
    $voucher = Receipt::where('id',$voucher_id)->first();
    return view('voucher.edit' ,  ['voucher' => $voucher  ]);  
}

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

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

    Receipt::where('id', $voucher_id)->update($fields);

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


    return redirect ( "/receipt/edit/$voucher_id" );

}



}
