<?php

namespace App\Http\Controllers\Accounting;

use Carbon\Carbon;
use App\Models\Income;
use App\Models\IncomeHead;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
use App\Services\FundTransferService;

class IncomeController extends Controller
{

    public function __construct()
    {
        $this->middleware('permission:income-section|income-entry|income-head|income-report|other-income', ['only' => ['index', 'show']]);
        $this->middleware('permission:income-entry', ['only' => ['create', 'store']]);
        $this->middleware('permission:income-entry', ['only' => ['edit', 'update']]);
    }

    public function index()
    {
        $data = [
            'incomes' => Income::orderBy('id','desc')->paginate(1000),
        ];
        // $incomes = Income::all();
        //dd($data);
        return view('accounts.income.index', $data);
    }


    public function create()
    {
        $incomeHead = IncomeHead::all();
        return view('accounts.income.create', compact('incomeHead'));
    }


    public function store(Request $request)
    {
        $request->validate([
            'attach_document' => 'mimes:jpeg,jpg,png,webp,gif,pdf|max:10240',
            //       'teacher_id' => 'required|unique:subjects,name,' . $complain->id,
            // 'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|digits:11|unique:complains,phone,' . $request->id,
        ]);


        DB::beginTransaction();
        try {


            $income = new Income();
            $income->name = $request->name;
            $income->incomeHead = $request->incomeHead;
            $income->invoice_number = $request->invoice_number??'nan';
            $income->date = $request->date;
            $income->amount = $request->amount;
            $income->description = $request->description;

            if ($request->attach_document != null) {
                $fileName = time() . '.' . $request->attach_document->extension();
                $request->attach_document->move(storage_path('app/public/attachDocument'), $fileName);
                $income->attach_document = $fileName;
            }

            $income->save();

            // dd($income->id);

            $note = 'Fund Added For: '.$request->name.' : '.$request->description;
            (new FundTransferService)->addFundToCash($request->amount,$note,$income->id,'income');



            DB::commit();
            return redirect()->route('income.index')->with('success_message','Income Added');


            //code...
        } catch (\Throwable $th) {
            //throw $th;
            DB::rollback();
        }

        // dd($request->all());

    }


    public function show(Income $income)
    {
        //
    }


    public function edit($id)
    {
        $income = Income::find($id);

        $data = [
            'model' => $income,
            'incomeHead' => IncomeHead::all(),
            'title' => 'Income'
        ];
        return view('accounts.income.edit', $data);
    }


    public function update(Request $request)
    {


        DB::beginTransaction();
        try {

            $income = Income::find($request->id);

            $income->name = $request->name;
            $income->incomeHead = $request->incomeHead;
            $income->invoice_number = $request->invoice_number??'nan';
            $income->date = $request->date;
            $income->amount = $request->amount;
            $income->description = $request->description;

            if ($request->attach_document != null) {
                File::delete(public_path('storage/attachDocument/' . $income->attach_document));
                $fileName = time() . '.' . $request->attach_document->extension();
                $request->attach_document->move(storage_path('app/public/attachDocument'), $fileName);
                $income->attach_document = $fileName;
            }
            $income->update();





            $note = 'Fund Added For: '.$request->name.' : '.$request->description;
            (new FundTransferService)->modifyAddFundToCash($request->amount,$note,$income->id,'income');

            DB::commit();

            return redirect()->route('income.index')->with("success_message",'Income Updated');

        } catch (\Throwable $th) {
            //throw $th;
        }

    }


    public function destroy(Income $income)
    {
        $income->delete();
        return redirect()->route('income.index');
    }

    public function incomeReport()
    {
        //dd('hello');
        $start = Carbon::now()->today()->firstOfMonth();
        $end = today();
        $heads = IncomeHead::all();
        return view('accounts.incomeReport.index', [
            'start' => $start,
            'end'   =>$end,
            'heads' => $heads
        ]);
    }

    public function incomeSearchResult(Request $request)
    {

        $start = Carbon::parse($request->from_date)->format('Y-m-d 00:00:00');
        $end = Carbon::parse($request->to_date)->format('Y-m-d 23:59:59');

        // $incomes = Income::whereBetween('date', [$start, $end])->orderBy('id','DESC')->get();
        if($request->incomeHead == 'all'){
            $incomes = Income::whereBetween('date', [$start, $end])->orderBy('id','DESC')->get();
        }else{
            $incomes = Income::whereBetween('date', [$start, $end])->where('incomeHead',$request->incomeHead)->orderBy('id','DESC')->get();
        }

        $data = [
            'incomes' => $incomes,

        ];
        return view('accounts.incomeReport.result', $data);
    }
}
