<?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\Daily_Safe_Account;
use App\Bank;
use App\Receipt;
use App\Payment_Voucher;
use App\Cheque;
use App\Safe_History;
use App\Transfer;
use App\Invoice;
use App\Invoice_Item;
use App\Invoice_Payment;
use App\Tab;
use App\Notifications;
class SafeController 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 payment_method_show()
{
    $payment_methods = Payment_Method::get();
    return view('payment_method.show' , ['payment_methods' => $payment_methods]);
}
public function payment_method_create_get()
{   
    return view('payment_method.create');
}
public function payment_method_create(Request $request) {
    
    $payment_method = Payment_Method::create ( [ 		
            'name' => $request ['name']
    ] );    
    session()->flash('message', 'New payment_method Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/payment_method/index" );
}

public function payment_method_edit_get($payment_method_id){
    $payment_method = DB::table('payment_methods')->where('id', '=',$payment_method_id)->first();
    return view('payment_method.edit',[
                            'payment_method' => $payment_method
                            ]);
}
public function payment_method_edit_post(Request $request){
    $name = $request ['name'];
    $payment_method_id = $request ['payment_method_id']; 
    
   

    DB::table('payment_methods')
        ->where('id', $payment_method_id)
        ->update(['name' => $name,
         'updated_at' => Carbon::now()]);
            
    session()->flash('message', 'payment_method Updated successfully');
    session()->flash('type', 'success');

    return redirect ( "/payment_method/edit/$payment_method_id" );
}

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

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

//banks
public function bank_show()
{
    $banks = Bank::get();
    return view('bank.show' , ['banks' => $banks]);
}
public function bank_create_get()
{   
    return view('bank.create');
}
public function bank_create(Request $request) {
    
    $bank = Bank::create ( [ 		
            'name' => $request ['name']
    ] );    
    session()->flash('message', 'New Bank Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/bank/index" );
}

public function bank_edit_get($bank_id){
    $bank = DB::table('banks')->where('id', '=',$bank_id)->first();
    return view('bank.edit',[
                            'bank' => $bank
                            ]);
}
public function bank_edit_post(Request $request){
    $name = $request ['name'];
    $bank_id = $request ['bank_id']; 
    
   

    DB::table('banks')
        ->where('id', $bank_id)
        ->update(['name' => $name,
         'updated_at' => Carbon::now()]);
            
    session()->flash('message', 'bank Updated successfully');
    session()->flash('type', 'success');

    return redirect ( "/bank/edit/$bank_id" );
}

public function bank_delete($bank_id){
    
    $bank = Bank::find($bank_id);
    $bank->delete();
    return redirect ( "/bank/index");
}



////////////////////////////////////////////////////
//tabs
public function tab_show()
{
    $tabs = Tab::get();
    return view('tab.show' , ['tabs' => $tabs]);
}
public function tab_create_get()
{   
    return view('tab.create');
}
public function tab_create(Request $request) {
    
    $tab = Tab::create ( [ 		
            'name' => $request ['name']
    ] );    
    session()->flash('message', 'New tabutation Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/tab/index" );
}

public function tab_edit_get($tab_id){
    $tab = DB::table('tabs')->where('id', '=',$tab_id)->first();
    return view('tab.edit',[
                            'tab' => $tab
                            ]);
}
public function tab_edit_post(Request $request){
    $name = $request ['name'];
    $tab_id = $request ['tab_id']; 
    
   

    DB::table('tabs')
        ->where('id', $tab_id)
        ->update(['name' => $name,
         'updated_at' => Carbon::now()]);
            
    session()->flash('message', 'tab Updated successfully');
    session()->flash('type', 'success');

    return redirect ( "/tab/edit/$tab_id" );
}



public function tabulate_payment_voucher_get($payment_voucher_id){
    $tabs = Tab::get();
    return view('tab.tabulate',[
                            'tabs' => $tabs,
                            'payment_voucher_id'=>$payment_voucher_id,
                            'kind'=>'payment_voucher',
                            ]);
}

public function tabulate_voucher_get($voucher_id){
    $tabs = Tab::get();
    return view('tab.tabulate',[
                            'tabs' => $tabs,
                            'voucher_id'=>$voucher_id,
                            'kind'=>'voucher',
                            ]);
}

public function tabulate_post(Request $request){
    $tab_id = $request ['tab_id'];
    $sanad_id = $request ['sanad_id']; 
    $kind = $request ['kind'];

    if ($kind ==  "voucher"){

       DB::table('receipt')
        ->where('id', $sanad_id)
        ->update(['tab_id' => $tab_id,
         'updated_at' => Carbon::now()]);
            
    session()->flash('message', 'تم تبويب سند القبض بنجاح');
    session()->flash('type', 'success');

    return redirect ( "/tab/tabulate_voucher/$sanad_id" );

    }
    else {
    DB::table('payment_vouchers')
        ->where('id', $sanad_id)
        ->update(['tab_id' => $tab_id,
         'updated_at' => Carbon::now()]);
            
    session()->flash('message', 'تم تبويب سند الصرف بنجاح');
    session()->flash('type', 'success');

    return redirect ( "/tab/tabulate_payment_voucher/$sanad_id" );
    }

}

// safe account


// safe account


public function safe_account_show()
{
    $branch_id = Auth::user()->branch_id ;
    $safe_accounts = Safe_Account::with('branch','payment_method')
    ->where('branch_id' ,$branch_id)
    ->get();
    return view('safe_account.show' , ['safe_accounts' => $safe_accounts]);
}
public function safe_account_create_get()
{   
    $branches = Branch::get();
    $payment_methods = Payment_Method::get();
    return view('safe_account.create', [
        'branches' => $branches,
        'payment_methods'=>$payment_methods
        ]);
}
public function safe_account_create(Request $request) {
    
    $safe_account = Safe_Account::create ( [
            'branch_id' => $request ['branch_id'],
            'payment_method_id' => $request ['payment_method_id'],
            'balance' => $request ['balance']
    ] );    
    session()->flash('message', 'New safe_account Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/safe_account/index" );
}

public function safe_account_edit_get($safe_account_id){
    $safe_account = DB::table('safe_accounts')->where('id', '=',$safe_account_id)->first();
    return view('safe_account.edit',[
                            'safe_account' => $safe_account
                            ]);
}
public function safe_account_edit_post(Request $request){
    $name = $request ['name'];
    $safe_account_id = $request ['safe_account_id']; 
    
   

    DB::table('safe_accounts')
        ->where('id', $safe_account_id)
        ->update(['name' => $name,
         'updated_at' => Carbon::now()]);
            
    session()->flash('message', 'safe_account Updated successfully');
    session()->flash('type', 'success');

    return redirect ( "/safe_account/edit/$safe_account_id" );
}

public function safe_account_delete($safe_account_id){
    
    $safe_account = Safe_Account::find($safe_account_id);
    $safe_account->delete();
    return redirect ( "/safe_account/index");
}

public function safe_account_feed_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();
    return view('safe_account.feed',[
        'accounts' => $accounts,
        'banks'=>$banks
    ]);

}


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

   
  
    $safe_account = Safe_Account::where( 'id', $receipt->safe_account_id)->first(); 
    
    
        
        Safe_History::insert ( 
            [ 	'balance_before' => $safe_account->balance,
                'descreption' => " $receipt->note1  -  $receipt->note2",
                'receipt_id'  => $receipt->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;
$safe_account_name = $safe_account->payment_method->name;
$final_name= "". $safe_account_name ." ". $branch_name;
$action =" تنبيه تغذية خزنة ";
$general_name= $request ['name'];
$n = Notifications::create ( [  'type'=>$action,
'action'=> " قام المستخدم $admin_name بأستلام مبلغ $pay جينيه و ايداعه بالخزنة $final_name من طرف $general_name وذلك بموجب سند قبض رقم $receipt_id " ] );

$this->SendNotification ( " قام المستخدم $admin_name بأستلام مبلغ $pay جينيه و ايداعه بالخزنة $final_name من طرف $general_name وذلك بموجب سند قبض رقم $receipt_id ");

//end notifivation


    session()->flash('message', 'Feed Done Successfully');
    session()->flash('type', 'success');
    return redirect ( "/safe_account/feed" );

}


public function safe_account_transfer_get(){

    $branch_id = Auth::user()->branch_id ;
    $accounts = Safe_Account::with('payment_method','branch')->where('branch_id',$branch_id)->get();
    return view('safe_account.transfer',[
        'accounts' => $accounts
    ]);

}


public function safe_account_transfer_post (Request $request){

    $safe_account_id_from = $request ['safe_account_id_from'];
    $safe_account_id_to = $request ['safe_account_id_to'];
    $amount = $request ['amount'];

    $from_safe_account = Safe_Account::where( 'id', $safe_account_id_from)->first();
    $to_safe_account = Safe_Account::where( 'id', $safe_account_id_to)->first();
    if ($from_safe_account->balance < $amount ) {
        session()->flash('message', 'Transfer Money Fail , no enough money');
    session()->flash('type', 'danger');
    return redirect ( "/safe_account_transfer/create" );
    }
    
    
        $name_to=  $to_safe_account->payment_method->name;
    $name_from = $from_safe_account->payment_method->name;


        Safe_History::insert ( 
            [ 	'balance_before' => $from_safe_account->balance,
                'descreption' => "  تحول من      $name_from        الي       $name_to  ",
                'user_id' => Auth::user()->id,
                'safe_account_id'=>$from_safe_account->id,
                'movement_type'=> "تحويل من",
                "outcome"=>$amount,
                'balance_after' =>  $from_safe_account->balance - $amount ,
     ]);
    
    Safe_History::insert ( 
            [ 	'balance_before' => $to_safe_account->balance,
                'descreption' => "  تحول من      $name_from        الي       $name_to  ", 
                'user_id' => Auth::user()->id,
                'safe_account_id'=>$to_safe_account->id,
                'movement_type'=> "تحويل الي",
                "income"=>$amount,
                'balance_after' =>  $to_safe_account->balance + $amount ,
            ]);
    
    
    DB::table('safe_accounts')
        ->where('id', $safe_account_id_from)
        ->update([ 'balance' => DB::raw("balance-$amount"),
                'updated_at' => Carbon::now()
        ]);

    DB::table('safe_accounts')
        ->where('id', $safe_account_id_to)
        ->update([ 'balance' => DB::raw("balance+$amount"),
                'updated_at' => Carbon::now()
        ]);
 
    Transfer::insert ( 
        [ 	'sender_id' => $safe_account_id_from ,
            'receiver_id' =>  $safe_account_id_to ,
            'amount' => $amount,
            'des' => NULL,
        ]);
    session()->flash('message', 'Transfer Money Done Successfully');
    session()->flash('type', 'success');
    return redirect ( "/safe_account_transfer/create" );
}


////////////////////////////////////////////
// الحسابات اليومية للخزنة 
/////////////////////////////////////////////

public function get_last_safe_accounts (){
    $branch_id = Auth::user()->branch_id ;
   
    
    $last_row_inserted = Daily_Safe_Account::latest('created_at')->where('branch_id',$branch_id)->first();
     
    $last_created_at = $last_row_inserted ? $last_row_inserted->created_at : NULL ;
    
    //$dt = new DateTime($last_created_at);
    $last_cr_at =  Carbon::parse($last_created_at)->format('Y-m-d');
    
    $date_now =  Carbon::now()->format('Y-m-d');
    
    if ($last_cr_at < $date_now  or !$last_row_inserted ) {
         
        return view('safe_account.daily', [
        'daily_safe_account' => [],
        'total_balance'=>0,
        'total_reciept_pay'=>0,
        'total_payment_vouchers'=>0,
        'cheques'=>[],
        'receipts'=>[],
        'payment_vouchers'=>[],
        'show_button'=>'yes'
        ]);
        
    }

    //$daily_safe_account = Daily_Safe_Account::where('created_at',$last_created_at  )->where('branch_id',$branch_id)->get();
    //$total_balance  = $daily_safe_account->sum('balance');

    
    $invoices = Invoice::where('branch_id', $branch_id)
    ->whereDate( 'created_at',"=",  Carbon::now()->format('Y-m-d') )
    ->orderBy('id', 'desc')
    ->get();
    
    $receipts = Receipt::with('tab')->whereDate( 'created_at',"=",  Carbon::now()->format('Y-m-d') )
->where('branch_id', $branch_id)
->get();
    //$total_reciept_pay  = $receipts->sum('pay');

    $payment_vouchers = Payment_Voucher::where('approve',"Approved")->whereDate( 'created_at',"=",  Carbon::now()->format('Y-m-d') )
->where('branch_id', $branch_id)
->get();
    //$total_payment_vouchers  = $payment_vouchers->sum('pay');
    

    $cheques = Cheque::where('date','>=',Carbon::now()->format('Y-m-d'))
->where('branch_id', $branch_id)
->get();

    $payment_vouchers = Payment_Voucher::with('tab')->whereDate( 'created_at',"=",  Carbon::now()->format('Y-m-d') )
->where('branch_id', $branch_id)
->where('approve', 'Approved')
->get();

    return view('safe_account.daily', [
        //'daily_safe_account' => $daily_safe_account,
        //'total_balance'=>$total_balance,
        //'total_reciept_pay'=>$total_reciept_pay,
        //'total_payment_vouchers'=>$total_payment_vouchers,
        'invoices'=>$invoices,
        'cheques'=>$cheques,
        'receipts'=>$receipts,
        'payment_vouchers'=>$payment_vouchers,
        'show_button'=>'no'
        ]);
}

public function start_day(){

    
    $branch_id = Auth::user()->branch_id ;
    $accounts = Safe_Account::where('branch_id', $branch_id)->get();
    $date_now =  Carbon::now()->format('Y-m-d H:i:s');

    foreach ($accounts as $key => $account) {
        $data [] = [
            'branch_id' => $account->branch_id,
            'payment_method_id' => $account->payment_method_id,
            'balance' => $account->balance,
            'created_at'=>$date_now
        ];
    }

     
     Daily_Safe_Account::insert($data);

   return redirect ( "/dailysafeaccount/index");
     //return redirect ("/sort");
}



public function safe_history_get()
{
    $branch_id = Auth::user()->branch_id ;
    $safe_accounts = Safe_Account::where('branch_id', $branch_id)->get();
    return view('safe_account.safehistorycreate' , ['safe_accounts' => $safe_accounts]);
}


public function getSafeAccounts(Request $request)
    {
       
         $branch_id = Auth::user()->branch_id ;
         $dateFrom = $request ['from'];
         $dateTo = $request ['to'];
        
        try {
        
    $safe_accounts = Safe_History::with('safe_account')
    ->join('safe_accounts', 'safe_history.safe_account_id', '=', 'safe_accounts.id')
    ->join('payment_methods', 'safe_accounts.payment_method_id', '=', 'payment_methods.id')
    ->where('safe_accounts.branch_id', $branch_id)
    ->where('safe_history.created_at', '>=', $dateFrom)
    ->where('safe_history.created_at', '<=', $dateTo)
    ->select(
        'safe_history.safe_account_id',
        'payment_methods.name as payment_method_name'
    )
    ->distinct()
    ->get();

            return response()->json([
                'success' => true,
                'safe_accounts' => $safe_accounts,
                
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'حدث خطأ: ' . $e->getMessage()
            ], 500);
        }
    }

public function safe_history_post(Request $request) {
    
        $user_name = Auth::user()->name ;
        $bransh_name = Auth::user()->branch->name ;

        $safe_account_id = $request ['safe_account_id'];
        $dateFrom = $request ['from'];
        $dateTo = $request ['to'];
        
        $safe_account = Safe_Account::where( 'id', $safe_account_id)->first();
        
        $history = Safe_History::with('safe_account')-> where( [ 
                ['safe_account_id', '=',$safe_account_id]
                ])->whereDate( 'created_at',">=", $dateFrom)->whereDate('created_at',"<=", $dateTo )->get();

        
         return view('safe_account.safehistoryshow', [
            'history'=>$history , 
            'user_name'=>$user_name,
            'bransh_name'=>$bransh_name,
            'dateFrom'=>$dateFrom,
            'dateTo'=>$dateTo,
            'safe_account'=>$safe_account

        ]);
    
    }







}
