<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Bank;
use App\Models\Company;
use App\Models\Expense;
use App\Models\FixedExpense;
use App\Models\PreSettings;
use App\Models\Safe;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class ExpenseController 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' => ['fixed_expenses']]);
        $this->middleware('permission:إضافة مصروف ثابت', ['only' => ['fixed_expenses_store']]);
        $this->middleware('permission:تعديل مصروف ثابت', ['only' => ['fixed_expenses_edit','fixed_expenses_update']]);
        $this->middleware('permission:حذف مصروف ثابت', ['only' => ['fixed_expenses_destroy']]);
    }

    public function fixed_expenses(){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $fixed_expenses = FixedExpense::where('company_id',$company_id)->get();
        return view('client.expenses.fixed', compact('company', 'company_id', 'fixed_expenses'));
    }
    public function fixed_expenses_store(Request $request){
        $this->validate($request, [
            'fixed_expense' => 'required'
        ]);
        $data = $request->all();
        $company_id = $data['company_id'];
        $data['client_id'] = Auth::user()->id;
        $fixed_expense = FixedExpense::create($data);
        return response()->json(['status'=>true,'message'=>'تم إضافة المصروف الثابت بنجاح']);

    }

    public function fixed_expenses_edit($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $fixed_expense = FixedExpense::findOrFail($id);
        return view('client.expenses.fixed_edit', compact('fixed_expense', 'company_id', 'company'));
    }
    public function fixed_expenses_update(Request $request)
    {
        $this->validate($request, [
            'fixed_expense' => 'required'
        ]);
        $data = $request->all();
        $company_id = $data['company_id'];
        $data['client_id'] = Auth::user()->id;
        $fixed_expense = FixedExpense::FindOrFail($request->id);
        $fixed_expense->update($data);
        return response()->json(['status'=>true,'message'=>'تم تعديل البيانات بنجاح']);

    }

    public function fixed_expenses_destroy(Request $request)
    {
        FixedExpense::FindOrFail($request->id)->delete();
        return response()->json(['status'=>true,'message'=>'تم الحذف بنجاح']);

    }

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

    public function create()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $fixed_expenses = FixedExpense::where('company_id',$company_id)->get();
        $safes = Safe::where('company_id',$company_id)->get();
        $banks = Bank::where('company_id',$company_id)->get();
        return view('client.expenses.create', compact('company_id','safes','banks','fixed_expenses','company'));
    }

    public function store(Request $request)
    {

        $this->validate($request, [
            'type' => 'required',
            'fixed_expense' => 'required',
            'expense_details' => 'required',
            'amount' => 'required',
            
        ]);
        if(empty($request->bank_id) && empty($request->safe_id)){
            return response()->json(['status'=>false,'message'=>'يجب اختيار الخزينة أو البنك']);
        }
        $data = $request->all();
        $company_id = $data['company_id'];
        $data['client_id'] = Auth::user()->id;
        $data['expense_number'] = $this->get_expense_number();

        if($request->type =='إيراد'){
        $data['amount'] = $data['amount'];
        }elseif($request->type =='مصروف'){
        $data['amount'] = -$data['amount'];
        }
        $expense = Expense::create($data);
        if ($request->hasFile('expense_pic')) {
            $expense_pic = $request->file('expense_pic');
            $fileName = $expense_pic->getClientOriginalName();
            $uploadDir = 'uploads/expenses/' . $expense->id;
            $expense_pic->move($uploadDir, $fileName);
            $expense->expense_pic = $uploadDir . '/' . $fileName;
            $expense->save();
        }
        if($request->bank_id){
            $bank_id = $data['bank_id'];
            $bank = Bank::FindOrFail($bank_id);
            $old_balance = $bank->bank_balance;
            $new_balance = $old_balance + $data['amount'];
            $bank->update([
                'bank_balance' => $new_balance,
            ]);
        }elseif($request->safe_id){
        $safe_id = $data['safe_id'];
        $safe = Safe::FindOrFail($safe_id);
        $old_balance = $safe->balance;
        $new_balance = $old_balance + $data['amount'];
        $safe->update([
            'balance' => $new_balance,
        ]);
        }
        return response()->json(['status'=>true,'message'=>'تم إضافة المصروف بنجاح']);
    }

    public function edit($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $expense = Expense::findOrFail($id);
        $fixed_expenses = FixedExpense::where('company_id',$company_id)->get();
        $safes = Safe::where('company_id',$company_id)->get();
        $banks = Bank::where('company_id',$company_id)->get();
        return view('client.expenses.edit', compact('banks','expense','fixed_expenses','safes', 'company_id', 'company'));
    }

    public function update(Request $request)
    {
        $this->validate($request, [
            'fixed_expense' => 'required',
            'expense_details' => 'required',
            'amount' => 'required',
        ]);

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

        $data = $request->all();
        $company_id = $data['company_id'];
        $data['client_id'] = Auth::user()->id;
        $expense = Expense::FindOrFail($request->id);

        if($expense->safe_id){
        $old_safe_id = $expense->safe_id;
        $old_safe = Safe::FindOrFail($old_safe_id);
        $old_safe_amount = $expense->amount;
        $old_safe_balance = $old_safe->balance;
        $new_safe_balance = $old_safe_balance + $old_safe_amount;
        $old_safe->update([
            'balance' => $new_safe_balance,
        ]);
        }
        if($expense->bank_id){
        $old_bank_id = $expense->bank_id;
        $old_bank = Bank::FindOrFail($old_bank_id);
        $old_bank_amount = $expense->amount;
        $old_bank_balance = $old_bank->bank_balance;
        $new_bank_balance = $old_bank_balance + $old_bank_amount;
        $old_bank->update([
            'bank_balance' => $new_bank_balance,
        ]);

        }   

        if($request->safe_id != null){
        $safe_id = $data['safe_id'];
        $safe = Safe::FindOrFail($safe_id);
        $old_amount = $expense->amount;
        $old_balance = $safe->balance;
        $new_balance = $old_balance - $data['amount'];
        $safe->update([
            'balance' => $new_balance,
        ]);
        }
        if($request->bank_id != null){
        $bank_id = $data['bank_id'];
        $bank = Bank::FindOrFail($bank_id);
        $old_balance = $bank->bank_balance;
        $new_balance = $old_balance - $data['amount'];
        $bank->update([
            'bank_balance' => $new_balance,
        ]);
        }

        $expense->update($data);
        if ($request->hasFile('expense_pic')) {
            $expense_pic = $request->file('expense_pic');
            $fileName = $expense_pic->getClientOriginalName();
            $uploadDir = 'uploads/expenses/' . $expense->id;
            $expense_pic->move(public_path($uploadDir), $fileName);
            $expense->expense_pic = $uploadDir . '/' . $fileName;
            $expense->save();
        }

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

    }

    public function delete(Request $request)
    {
        $expense =   Expense::findOrFail($request->id);

        if($expense->safe_id){
            $old_safe_id = $expense->safe_id;
            $old_safe = Safe::FindOrFail($old_safe_id);
            $old_safe_amount = $expense->amount;
            $old_safe_balance = $old_safe->balance;
            $new_safe_balance = $old_safe_balance + $old_safe_amount;
            $old_safe->update([
                'balance' => $new_safe_balance,
            ]);
            }
            if($expense->bank_id){
            $old_bank_id = $expense->bank_id;
            $old_bank = Bank::FindOrFail($old_bank_id);
            $old_bank_amount = $expense->amount;
            $old_bank_balance = $old_bank->bank_balance;
            $new_bank_balance = $old_bank_balance + $old_bank_amount;
            $old_bank->update([
                'bank_balance' => $new_bank_balance,
            ]);
    
            }  

        $expense->delete();

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

    public function get_expense_number(){
        $company_id = auth()->user()->company_id;
        $check = Expense::where('company_id',$company_id)->get();
        if ($check->isEmpty()) {
            $pre_settings = PreSettings::where('company_id', $company_id)->first();
            $pre_expenses = $pre_settings->pre_expenses;
        } else {
            $old_expense = Expense::max('expense_number');
            $pre_expenses = ++$old_expense;
        }

        return $pre_expenses;
    }
}
