<?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\Client_Sheet;
use App\Invoice_Item;
use App\Invoice_Payment;
use \stdClass;
use App\Invoice;
use App\Receipt;
use App\Review;
use App\Review_Item;
use App\Discount;
use App\Payment_Voucher;
use App\Notifications;

class ClientController 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);


}


     
//////////////////////////////////////////////////
// payment method

public function client_show()
{

    $branch_id = Auth::user()->branch_id ;
    $clients = Client::where('branch_id' ,$branch_id )->get();
    return view('client.show' , ['clients' => $clients]);
}



public function client_all_accounts()
{
    $branch_id = Auth::user()->branch_id ;
    $clients = Client::where('branch_id' ,$branch_id )->get();
    $final_arr=[];

    $total_start_leeh=0;
    $total_start_aleeh=0;
    $total_total_leeh=0;
    $total_total_aleeh=0;
    $rejected_cheeques=0;
    
     $sum_last_moda_leeh = 0 ;  //دائن رصيد اخر المدة
    $sum_last_moda_aleeh = 0 ;  // رصيد اخر المدة مدين
    
    foreach ($clients as $client) {
        $total_leeh =  Client_Sheet::where('client_id' ,$client->id)->sum('leeh');  // دفع
        $total_aleeh = Client_Sheet::where('client_id' ,$client->id)->sum('aleeh');  // خد 

        // rejected cheque
        $rejected_cheeques = Client_Sheet::where('client_id' ,$client->id)
                                         ->where('invoice_id' ,NULL)
                                         ->where('receipt_id' ,NULL)
                                         ->sum('refused_cheque');  // دفع
        $obj = new stdClass();
        $obj->name = $client->name;
        $obj->id = $client->id;
        $obj->start_leeh= $client->start_leeh;  
        $obj->start_aleeh = $client->start_aleeh;   
        $obj->total_leeh = $total_leeh - $rejected_cheeques;  
        $obj->total_aleeh = $total_aleeh - $rejected_cheeques;  
        $obj->rejected_cheeques=$rejected_cheeques;

        //echo "$client->id -  (r $rejected_cheeques )  ,";
        // tfooter 
        $total_start_leeh = $total_start_leeh +   $client->start_leeh ; // sum اول 
        $total_start_aleeh = $total_start_aleeh + $client->start_aleeh; // sum اول 
        $total_total_leeh = $total_total_leeh +   $total_leeh - $rejected_cheeques;  // sum حركة
        $total_total_aleeh = $total_total_aleeh + $total_aleeh - $rejected_cheeques; // sum حركة

if ( $total_leeh >$total_aleeh ) {
    $sum_last_moda_leeh = $sum_last_moda_leeh + ( $total_leeh-$total_aleeh ) ;
   }else{
    $sum_last_moda_aleeh = $sum_last_moda_aleeh + ( $total_aleeh-$total_leeh ) ;
  }
  
        $final_arr[]=$obj;
    }

    //var_dump ($final_arr);
    return view('client.show_accounts' , ['clients' => $final_arr , 
                                        "total_start_leeh"=>$total_start_leeh , 
                                        "total_start_aleeh"=>$total_start_aleeh,
                                        "total_total_leeh"=>$total_total_leeh ,
                                        "total_total_aleeh"=>$total_total_aleeh,
                                "sum_last_moda_leeh" =>$sum_last_moda_leeh,
                                "sum_last_moda_aleeh"=>$sum_last_moda_aleeh ]);
}

public function create_sheet_get(){

    $branch_id = Auth::user()->branch_id ;
    $clients = Client::where('branch_id' ,$branch_id )->get();
    return view('client.sheet_create' , ['clients' => $clients]);

}


public function create_sheet_post(Request $request){

   // $invoices = Invoice::where('client_id',1)->where('confirmed',"confirmed")->get();
    
    $client_id = $request ['client_id'];

    $from = $request ['from'];
    $to = $request ['to'];
    $clientrow = DB::table('clients')->where('id', '=',$client_id)->first();

    $client_sheets = Client_Sheet::where('client_id',$client_id)
    ->whereDate('created_at','>=',$from)
    ->whereDate('created_at','<=',$to)->orderBy('created_at', 'asc')->get();  // in time range
    
    

    $final_arr = [];
    foreach ($client_sheets as $client_sheet ){

      $previos_sum_leeh =  Client_Sheet::where('client_id' ,$client_id)->where('created_at' ,'<', $client_sheet->created_at)->sum('leeh');  // دفع
      $previos_sum_aleeh = Client_Sheet::where('client_id' ,$client_id)->where('created_at' ,'<',$client_sheet->created_at)->sum('aleeh');  // خد 
      // الحساب السابق
      $previos = $previos_sum_leeh > $previos_sum_aleeh ? -1* ($previos_sum_leeh - $previos_sum_aleeh) : ($previos_sum_aleeh - $previos_sum_leeh) ;
      
       

      $current_sum_leeh =  Client_Sheet::where('client_id' ,$client_sheet->client_id)->where('created_at' ,'<=', $client_sheet->created_at)->sum('leeh');  // دفع
      $current_sum_aleeh = Client_Sheet::where('client_id' ,$client_sheet->client_id)->where('created_at' ,'<=',$client_sheet->created_at)->sum('aleeh');  // خد 
      // الحساب الحالي 
      $current = $current_sum_leeh > $current_sum_aleeh ? - ($current_sum_leeh - $current_sum_aleeh) : ($current_sum_aleeh - $current_sum_leeh) ;
     
      $invoice_items = Invoice_Item::with('invoice')->where('invoice_id', $client_sheet->invoice_id  )->get();
      $payment_methods = Invoice_Payment::with('invoice')->where('invoice_id', $client_sheet->invoice_id  )->get();
      
      //  sanad kabd calculated only if you entered manual sand kabd , not calculated in the invoice 
      $receipts = Receipt::where('id', $client_sheet->receipt_id  )->get();
      $review_items = Review_Item::where('review_id', $client_sheet->review_id)->get();

      $review = Review::where('id', $client_sheet->review_id)->first();
      //echo $reviews->items;
      
      $discounts = Discount::where('id', $client_sheet->discount_id  )->get();  //discount added here

      $obj = new stdClass();
      $obj->previos = $previos;
      $obj->current = $current;
      $obj->items= $invoice_items;
      $obj->receipts=$receipts;
      $obj->payment_methods=$payment_methods;
      $obj->review_items=$review_items;
      $obj->review=$review;
      $obj->discounts=$discounts;  //discount added here
      $obj->final_state = $current > 0 ? "مدين" : "دائن";
      $final_arr[]=$obj;

    }

    //return 0 ;
    //var_dump ($invoices);
    //$invoice_items = Invoice_Item::with('invoice')->get();
    //  all cheeques that rejected  ==>aleeh
  

    return view('client.sheet' , ['client_sheets' => $final_arr, "client"=>$clientrow, "from"=>$from , "to"=>$to]);   
}



public function client_create_get()
{   
    return view('client.create');
}
public function client_create(Request $request) {
    
    $branch_id  =  Auth::user()->branch_id ;

    $client = Client::create ( [ 		
        'client_kind' => $request ['client_kind'],
        'client_state' => $request ['client_state'],
        'client_class' => $request ['client_class'],
        'trade_kind' => $request ['trade_kind'],
        'name' => $request ['name'],
        'address' => $request ['address'],
        'gov' => $request ['gov'],
        'mobile' => $request ['mobile'],
        'email' => $request ['email'],
        'ct' => $request ['ct'],
        'bd' => $request ['bd'],
        'credit_limit' => $request ['credit_limit'],
        'start_leeh' => $request ['start_leeh'],
        'start_aleeh' => $request ['start_aleeh'],
        'branch_id' => $branch_id ,
] );     

Client_Sheet::insert ( 
    [ 		
        'leeh' => $request ['start_leeh'],
        'aleeh' => $request ['start_aleeh'] ,
        'client_id' => $client->id,
        'invoice_id'  => NULL
    ]);

    session()->flash('message', 'New Client Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/client/index" );
}

public function client_edit_get($client_id){
    $client = DB::table('clients')->where('id', '=',$client_id)->first();
    return view('client.edit',[
                            'client' => $client
                            ]);
}
public function client_edit_post(Request $request){
    
    $client_id = $request ['client_id']; 
    
   

    DB::table('clients')
        ->where('id', $client_id)
        ->update( [
        'client_kind' => $request ['client_kind'],
        'client_state' => $request ['client_state'],
        'client_class' => $request ['client_class'],
        'trade_kind' => $request ['trade_kind'],
        'name' => $request ['name'],
        'address' => $request ['address'],
        'gov' => $request ['gov'],
        'mobile' => $request ['mobile'],
        'email' => $request ['email'],
        'ct' => $request ['ct'],
        'bd' => $request ['bd'],
        'credit_limit' => $request ['credit_limit'],
       // 'start_leeh' => $request ['start_leeh'],
       // 'start_aleeh' => $request ['start_aleeh'],
         'updated_at' => Carbon::now()
         ]);
            
 /*           
  Client_Sheet::insert ( 
    [ 		
        'leeh' => $request ['start_leeh'],
        'aleeh' => $request ['start_aleeh'] ,
        'client_id' => $client_id,
        'invoice_id'  => NULL
    ]);
    
    */
    
    session()->flash('message', 'Client Updated successfully');
    session()->flash('type', 'success');

    return redirect ( "/client/edit/$client_id" );
}

public function client_delete($payment_method_id){
    
    $payment_method = Payment_Method::find($payment_method_id);
    $payment_method->delete();
    return redirect ( "/payment_method/index");
}


     

public function discount_create_get(){
    $branch_id = Auth::user()->branch_id ;
    $clients = Client::where('branch_id' ,$branch_id )->get();
   return view('discount.create', ['clients' => $clients]);
}


public function discount_create_post( Request $request ){
    $branch_id = Auth::user()->branch_id ;
    $client_id = $request ['client_id'];
    $value = $request ['value'];
    $reason = $request ['reason'];
    
    
    
    
    
    $discount = Discount::create ( [ 		
        'value' => $value,
        'client_id' => $client_id,
        'branch_id' => $branch_id ,
        'reason'=>$reason
    ] );    
    
    
        //added for notifivation
$pay=$value;
$admin_name = Auth::user()->name ;
$branch_name = Auth::user()->branch->name ;
$client = Client::where( 'id', $client_id )->first(); 
$client_name = $client->name;
$action =" أشعار خصم  ";
$n = Notifications::create ( [  'type'=>$action,
'action'=> " قام المستخدم $admin_name بتسجيل خصم بمبلغ  $pay الي العميل $client_name بفرغ $branch_name  /  $reason"] );

$this->SendNotification (  " قام المستخدم $admin_name بتسجيل خصم بمبلغ  $pay الي العميل $client_name بفرغ $branch_name  /  $reason" );

//end notifivation



      return back()->with('success', 'Discount  Added successfully');
   
}

public function show(){
    $branch_id = Auth::user()->branch_id ;
    $discounts = Discount::where('branch_id' ,$branch_id )->get();
   return view('discount.show', ['discounts' => $discounts]);
}

public function getDiscountDetails($discount__id)
{
    $discount = Discount::findOrFail($discount__id);
     
     return view('discount.details', ['discount' => $discount]);
}



public function discount_save_status( Request $request ){
    $branch_id = Auth::user()->branch_id ;
    $discount_id = $request ['discount_id'];
    $client_id = $request ['client_id'];
    $status = $request ['status'];
    $setlement_method = $request ['setlement_method'];
    $value = $request ['value'];
    $payment_voucher_id = NULL;
    if ( $setlement_method == 2 ) {  // رد منفصل ليه سند صرف
        $payment_voucher_id = $request['payment_voucher_id'];
        $check =  Payment_Voucher::where('id', $payment_voucher_id)->
        where('approve','Approved')->where('pay', $value)->exists();
        if (!$check){
                return back()->with('error', ' سند الصرف غير موجود أو غير متوافق عليه او مرفوض !!');
        }
    }
    
    if ( $status == "Rejected" ) {  // رفض الخصم
         DB::table('discount')
        ->where('id', $discount_id)
        ->update([
         'status' => $status,
         'updated_at' => Carbon::now()
        ]);
      return back()->with('success', 'Discount  Rejected !!');
    }



         
        DB::table('discount')
        ->where('id', $discount_id)
        ->update([
         'status' => $status,
         'setlement_method'=>$setlement_method,
         'payment_voucher_id'=>$payment_voucher_id,
         'updated_at' => Carbon::now()
        ]);


if ( $setlement_method == 2 ) {
$newRecord = Client_Sheet::create([
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
                'leeh' => 0,
                'aleeh' =>$value,
                'client_id' => $client_id,
                'receipt_id' => null,
                'refused_cheque' => null,
                'discount_id' => $discount_id
            ]);
}else{

        $newRecord = Client_Sheet::create([
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
                'leeh' => $value,
                'aleeh' => 0,
                'client_id' => $client_id,
                'receipt_id' => null,
                'refused_cheque' => null,
                'discount_id' => $discount_id
            ]);
}

      return back()->with('success', 'Discount Added successfully');
        
   
   
}




}
