<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Bank;
use App\Models\Company;
use App\Models\Employee;
use App\Models\EmployeeCash;
use App\Models\Safe;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class EmployeeController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:قائمة الموظفين', ['only' => ['index']]);
        $this->middleware('permission:إضافة موظف', ['only' => ['create','store']]);
        $this->middleware('permission:تعديل موظف', ['only' => ['edit','update']]);
        $this->middleware('permission:حذف موظف', ['only' => ['delete']]);

        $this->middleware('permission:سجل سلف الموظف', ['only' => ['get_borrow']]);
        $this->middleware('permission:إعطاء سلفة إلي موظف', ['only' => ['post_borrow']]);
        $this->middleware('permission:تعديل سلفة إلي موظف', ['only' => ['edit_borrow']]);
        $this->middleware('permission:حذف سلفة إلي موظف', ['only' => ['destroy_borrow']]);

        $this->middleware('permission:سجل دفعات الموظف', ['only' => ['get_cash']]);
        $this->middleware('permission:إضافة دفعة إلي موظف', ['only' => ['post_cash']]);
        $this->middleware('permission:تعديل دفعة إلي موظف', ['only' => ['edit_cash']]);
        $this->middleware('permission:حذف دفعة إلي موظف', ['only' => ['destroy_cash']]);
        

    }
    public function index(){

        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $employees = $company->employees;
        return view('client.employees.index',compact('company_id','company','employees'));
    }

    public function create()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $user = Auth::user();
        $type_name = $user->company->subscription->type->type_name;
        if ($type_name == "تجربة"){
            $employees_count = "غير محدود";
        }
        else{
            $employees_count = $user->company->subscription->type->package->employees_count;
        }
        $company_employees_count = $company->employees->count();
        if ($employees_count == "غير محدود") {
            return view('client.employees.create', compact('company_id', 'company'));
        }
        else{
            if($employees_count > $company_employees_count){
                return view('client.employees.create', compact('company_id', 'company'));
            }
            else{
                return redirect()->route('client.home')->with('error','باقتك الحالية لا تسمح بالمزيد من الموظفين');
            }
        }
    }

    public function store(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $this->validate($request, [
            'name' => 'required',
            'salary' => 'required',
            'work_status' => 'required',
        ]);
        $data = $request->all();


        $company_id = $data['company_id'];
        $company = Company::FindOrFail($company_id);

        $type_name = $company->subscription->type->type_name;
        if ($type_name == "تجربة"){
            $employees_count = "غير محدود";
        }
        else{
            $employees_count = $company->subscription->type->package->employees_count;
        }
        $company_employees_count = $company->suppliers->count();
        if ($employees_count == "غير محدود") {
            
        }
        else{
            if(!$employees_count > $company_employees_count){

                return response()->json(['message' => 'باقتك الحالية لا تسمح بالمزيد من الموظفين','status'=>false]);
            }
        }


        $balance_type = $request->balance_type;
        if ($balance_type == "for") {
            $data['balance'] =  $request->balance;
        } elseif ($balance_type == "on") {
            $data['balance'] = -1 * $request->balance;
        }
        $data['balance_start'] = $data['balance'];
        $client_id = Auth::user()->id;
        $data['client_id'] = $client_id;
        $employee = Employee::create($data);

        return response()->json([
            'status' => true,
            'message' => 'تم اضافة الموظف بنجاح',
        ]);
    }


    public function edit($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $employee = Employee::where('company_id',$company_id)->FindOrFail($id);
        return view('client.employees.edit', compact('company_id','employee', 'company'));
    }

    public function update(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $this->validate($request, [
            'name' => 'required',
            'salary' => 'required',
            'work_status' => 'required',
            'balance_start' => 'required',
        ]);
        $data = $request->all();
        $balance_type = $request->balance_type;
        if ($balance_type == "for") {
            $data['balance_start'] =  $request->balance_start;
        } elseif ($balance_type == "on") {
            $data['balance_start'] = -1 * $request->balance_start;
        }
        $employee = Employee::findOrFail($request->id);
        $data['employee_id'] = Auth::user()->id;
        $employee->update($data);

        return response()->json([
            'status' => true,
            'message' => 'تم تعديل الموظف بنجاح',
        ]);
    }

    public function delete(Request $request)
    {
        $employee = Employee::FindOrFail($request->id);
        $employee->delete();

        return response()->json([
            'status' => true,
            'message' => 'تم حذف الموظف بنجاح',
        ]);
    }



    public function get_cash($id){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $employee = Employee::where('company_id',$company_id)->findOrFail($id);
        $employee_cashs = EmployeeCash::where('company_id',$company_id)->where('employee_id',$id)->where('amount','>',0)->get();
        $safes = $company->safes;
        $banks = $company->banks;
        return view('client.employees.cashs.cash',compact('company','safes','company_id','employee','employee_cashs','banks'));
    }
    public function post_cash(Request $request){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $this->validate($request, [
            'employee_id' => 'required',
            'amount' => 'required',
            'date' => 'required',
        ]);

        if(empty($request->bank_id) && empty($request->safe_id)){
            return response()->json(['status'=>false,'message'=>'يجب اختيار الخزينة أو البنك']);
        }

        $data = $request->all();
        $data['client_id'] = Auth::user()->id;
        $amount = $data['amount'];

        if($request->safe_id){
        $safe_id = $data['safe_id'];
        $safe = Safe::FindOrFail($safe_id);
        $old_balance = $safe->balance;
        $new_balance = $old_balance - $amount;
        $safe->update([
            'balance' => $new_balance,
        ]);
        }elseif($request->bank_id){
        $bank_id = $data['bank_id'];
        $bank = Bank::FindOrFail($bank_id);
        $old_balance = $bank->bank_balance;
        $new_balance = $old_balance - $amount;
        $bank->update([
            'bank_balance' => $new_balance,
        ]);
        }
        $employee =Employee::FindOrFail($request->employee_id);
        $employee->update([
            'balance' => $employee->balance - $amount,
        ]);
        
        EmployeeCash::create($data);

        return response()->json([
            'status' => true,
            'message' => 'تم حفظ العملية بنجاح',
        ]);
        
    }
    public function edit_cash($id,$cash)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $employee_cash = EmployeeCash::where('company_id',$company_id)->where('employee_id',$id)->where('amount','>',0)->findOrFail($cash);
        $employee = Employee::where('company_id',$company_id)->findOrFail($id);
        $safes = $company->safes;
        $banks = $company->banks;
        return view('client.employees.cashs.edit_cash', compact('company_id','safes','employee','employee_cash', 'company','banks'));
    }

    public function update_cash(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $this->validate($request, [
            'employee_id' => 'required',
            'amount' => 'required',
            'date' => 'required',
        ]);

        if(empty($request->bank_id) && empty($request->safe_id)){
            return response()->json(['status'=>false,'message'=>'يجب اختيار الخزينة أو البنك']);
        }

        $data = $request->all();
        $data['client_id'] = Auth::user()->id;
        // return old values
        $employee_cash = EmployeeCash::FindOrFail($request->id);
        $employee =Employee::FindOrFail($request->employee_id);
        $old_amount = $employee_cash->amount;
        if($employee_cash->safe_id){
        $safe_id = $employee_cash->safe_id;
        $safe = Safe::FindOrFail($safe_id);
        $old_balance = $safe->balance;
        $new_balance = $old_balance + $old_amount;
        $safe->update([
            'balance' => $new_balance,
        ]);
        }elseif($employee_cash->bank_id){
        $bank_id = $employee_cash->bank_id;
        $bank = Bank::FindOrFail($bank_id);
        $old_balance = $bank->bank_balance;
        $new_balance = $old_balance + $old_amount;
        $bank->update([
            'bank_balance' => $new_balance,
        ]);
        }
        $employee->update([
            'balance' => $employee->balance + $old_amount,
        ]);

        // assign new values
        $company_id = $data['company_id'];
        $data['client_id'] = Auth::user()->id;
        $amount = $data['amount'];
        if($request->safe_id){
            $safe_id = $data['safe_id'];
            $safe = Safe::FindOrFail($safe_id);
            $old_balance = $safe->balance;
            $new_balance = $old_balance - $amount;
            $safe->update([
                'balance' => $new_balance,
            ]);
        }elseif($request->bank_id){
            $bank_id = $data['bank_id'];
            $bank = Bank::FindOrFail($bank_id);
            $old_balance = $bank->bank_balance;
            $new_balance = $old_balance - $amount;
            $bank->update([
                'bank_balance' => $new_balance,
            ]);
        }
        $employee->update([
            'balance' => $employee->balance - $amount,
        ]);
        $employee_cash->update($data);

        return response()->json([
            'status' => true,
            'message' => 'تم تحديث العملية بنجاح',
        ]);
    }
    public function destroy_cash(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $data = $request->all();
        // return old values
        $employee_cash = EmployeeCash::FindOrFail($request->id);
        $employee =Employee::FindOrFail($employee_cash->employee_id);
        $old_amount = $employee_cash->amount;
        if($employee_cash->safe_id){
        $safe_id = $employee_cash->safe_id;
        $safe = Safe::FindOrFail($safe_id);
        $old_balance = $safe->balance;
        $new_balance = $old_balance + $old_amount;
        $safe->update([
            'balance' => $new_balance,
        ]);
        }elseif($employee_cash->bank_id){
        $bank_id = $employee_cash->bank_id;
        $bank = Bank::FindOrFail($bank_id);
        $old_balance = $bank->bank_balance;
        $new_balance = $old_balance + $old_amount;
        $bank->update([
            'bank_balance' => $new_balance,
        ]);
        }
        $employee->update([
            'balance' => $employee->balance + $old_amount,
        ]);
        $employee_cash->delete();
        return response()->json([
            'status' => true,
            'message' => 'تم تحديث العملية بنجاح',
        ]);
    }





// # borrow 



public function get_borrow($id){
    $company_id = Auth::user()->company_id;
    $company = Company::FindOrFail($company_id);
    $employee = Employee::where('company_id',$company_id)->findOrFail($id);
    $employee_borrows = EmployeeCash::where('company_id',$company_id)->where('employee_id',$id)->where('amount','<',0)->get();
    $safes = $company->safes;
    $banks = $company->banks;
    return view('client.employees.borrows.borrow',compact('company','safes','company_id','employee','employee_borrows','banks'));
}
public function post_borrow(Request $request){
    $company_id = Auth::user()->company_id;
    $company = Company::FindOrFail($company_id);
    $this->validate($request, [
        'employee_id' => 'required',
        'amount' => 'required',
        'date' => 'required',
    ]);

    if(empty($request->bank_id) && empty($request->safe_id)){
        return response()->json(['status'=>false,'message'=>'يجب اختيار الخزينة أو البنك']);
    }

    $data = $request->all();
    $data['client_id'] = Auth::user()->id;
    $data['amount']=$amount=-$request->amount;

    if($request->safe_id){
    $safe_id = $data['safe_id'];
    $safe = Safe::FindOrFail($safe_id);
    $old_balance = $safe->balance;
    $new_balance = $old_balance + $amount;
    $safe->update([
        'balance' => $new_balance,
    ]);
    }elseif($request->bank_id){
    $bank_id = $data['bank_id'];
    $bank = Bank::FindOrFail($bank_id);
    $old_balance = $bank->bank_balance;
    $new_balance = $old_balance + $amount;
    $bank->update([
        'bank_balance' => $new_balance,
    ]);
    }
    $employee =Employee::FindOrFail($request->employee_id);
    $employee->update([
        'balance' => $employee->balance + $amount,
    ]);
    
    EmployeeCash::create($data);

    return response()->json([
        'status' => true,
        'message' => 'تم حفظ العملية بنجاح',
    ]);
    
}
public function edit_borrow($id,$borrow)
{
    $company_id = Auth::user()->company_id;
    $company = Company::FindOrFail($company_id);
    $employee_borrow = EmployeeCash::where('company_id',$company_id)->where('employee_id',$id)->where('amount','<',0)->findOrFail($borrow);
    $employee = Employee::where('company_id',$company_id)->findOrFail($id);
    $safes = $company->safes;
    $banks = $company->banks;
    return view('client.employees.borrows.edit_borrow', compact('company_id','safes','employee','employee_borrow', 'company','banks'));
}

public function update_borrow(Request $request)
{
    $company_id = Auth::user()->company_id;
    $company = Company::FindOrFail($company_id);
    $this->validate($request, [
        'employee_id' => 'required',
        'amount' => 'required',
        'date' => 'required',
    ]);

    if(empty($request->bank_id) && empty($request->safe_id)){
        return response()->json(['status'=>false,'message'=>'يجب اختيار الخزينة أو البنك']);
    }

    $data = $request->all();
    $data['client_id'] = Auth::user()->id;
    // return old values
    $employee_cash = EmployeeCash::FindOrFail($request->id);
    $employee =Employee::FindOrFail($request->employee_id);
    $old_amount = $employee_cash->amount;
    if($employee_cash->safe_id){
    $safe_id = $employee_cash->safe_id;
    $safe = Safe::FindOrFail($safe_id);
    $old_balance = $safe->balance;
    $new_balance = $old_balance - $old_amount;
    $safe->update([
        'balance' => $new_balance,
    ]);
    }elseif($employee_cash->bank_id){
    $bank_id = $employee_cash->bank_id;
    $bank = Bank::FindOrFail($bank_id);
    $old_balance = $bank->bank_balance;
    $new_balance = $old_balance - $old_amount;
    $bank->update([
        'bank_balance' => $new_balance,
    ]);
    }
    $employee->update([
        'balance' => $employee->balance - $old_amount,
    ]);

    // assign new values
    $company_id = $data['company_id'];
    $data['client_id'] = Auth::user()->id;
    $data['amount']=$amount=-$request->amount;
    if($request->safe_id){
        $safe_id = $data['safe_id'];
        $safe = Safe::FindOrFail($safe_id);
        $old_balance = $safe->balance;
        $new_balance = $old_balance + $amount;
        $safe->update([
            'balance' => $new_balance,
        ]);
    }elseif($request->bank_id){
        $bank_id = $data['bank_id'];
        $bank = Bank::FindOrFail($bank_id);
        $old_balance = $bank->bank_balance;
        $new_balance = $old_balance + $amount;
        $bank->update([
            'bank_balance' => $new_balance,
        ]);
    }
    $employee->update([
        'balance' => $employee->balance + $amount,
    ]);
    $employee_cash->update($data);

    return response()->json([
        'status' => true,
        'message' => 'تم تحديث العملية بنجاح',
    ]);
}
public function destroy_borrow(Request $request)
{
    $company_id = Auth::user()->company_id;
    $company = Company::FindOrFail($company_id);
    $data = $request->all();
    // return old values
    $employee_cash = EmployeeCash::FindOrFail($request->id);
    $employee =Employee::FindOrFail($employee_cash->employee_id);
    $old_amount = $employee_cash->amount;
    if($employee_cash->safe_id){
    $safe_id = $employee_cash->safe_id;
    $safe = Safe::FindOrFail($safe_id);
    $old_balance = $safe->balance;
    $new_balance = $old_balance - $old_amount;
    $safe->update([
        'balance' => $new_balance,
    ]);
    }elseif($employee_cash->bank_id){
    $bank_id = $employee_cash->bank_id;
    $bank = Bank::FindOrFail($bank_id);
    $old_balance = $bank->bank_balance;
    $new_balance = $old_balance - $old_amount;
    $bank->update([
        'bank_balance' => $new_balance,
    ]);
    }
    $employee->update([
        'balance' => $employee->balance - $old_amount,
    ]);
    $employee_cash->delete();
    return response()->json([
        'status' => true,
        'message' => 'تم تحديث العملية بنجاح',
    ]);
}


}
