<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Models\Productcategory;
use App\Models\Supplier;
use App\Models\SupplierAccount;
use App\Models\CustomerAccount;
use App\Models\WorkerAccount;
use App\Models\Loan;
use App\Models\Transaction;
use App\Models\Product;
use App\Models\Purchase;
use App\Models\Expense;
use App\Models\CashClosing;
use App\Models\PurchaseDetail;
use App\Models\PurchaseStock;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    function checkpermission($permission){
        $user = Auth::user();
        $roles = $user->roles;
        $permissions = $roles[0]->permissions;
        $access = false;
        foreach ($permissions as $p) {
            if ($p->permission_key == $permission) {
                $access = true;
                break;
            }
        }
        if ($access == false) {
           // return redirect()->back()->with('error_message', 'You Have No Permission For Access This Route');
            return \Redirect::to('dashboard-panel')->send()->with('error_message', 'You Have No Permission For Access This Route');
        }
    }
    function cashCheck($tdate){
        $transaction_date =  date('Y-m-d',strtotime($tdate));
        $cus_pay = CustomerAccount::whereDate('payment_date', $transaction_date)->sum('amount');
        $lo_receive = Loan::whereDate('transaction_date',$transaction_date)->sum('credit');
        $bank_wit = Transaction::whereDate('transaction_date',$transaction_date)->where('transaction_status','Withdraw')->sum('transaction_amount');
        /*------payment ------------*/
        $w_pay = WorkerAccount::whereDate('payment_date', $transaction_date)->sum('amount');
        $sup_pay = SupplierAccount::whereDate('payment_date', $transaction_date)->sum('amount');
        $lo_pay = Loan::whereDate('transaction_date',$transaction_date)->sum('debit');
        $expense = Expense::whereDate('expense_date',$transaction_date)->sum('expense_amount');
        $bank_depo = Transaction::whereDate('transaction_date',$transaction_date)->where('transaction_status','Deposit')->sum('transaction_amount');

        $receipt = $cus_pay + $lo_receive + $bank_wit;
        $payment = $sup_pay + $w_pay + $lo_pay + $bank_depo + $expense;
        /*-----lastday cash-----------*/
        $lastday_cash = CashClosing::whereDate('closing_date', '<=', $transaction_date)->latest('closing_date')->first();
        $cash = $lastday_cash != '' ? $lastday_cash->balance : 0;
        $balance = $receipt + $cash - $payment;
        return $balance;
    }
}
