<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use App\Http\Requests\FinancialYearRequest;
use App\Models\City;
use App\Models\Company;
use App\Models\Country;
use App\Models\FinancialYear;
use App\Models\StateModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F;
use Yajra\DataTables\Facades\DataTables;

class FinancialYearController extends Controller
{
  function __construct()
    {
        $this->middleware('permission:financial-year-list|financial-year-create|financial-year-edit|financial-year-delete', ['only' => ['index','store']]);
    }

    public function index(Request $request)
    {
      $data = FinancialYear::with('getComapnyName');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                        return $query->where('financial_year_name', 'like', '%'.$search_query.'%');
                    })
                    ->paginate($sort_by);

            return view('financialyear.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);

            return view('financialyear.index', compact('data'));
        }

    }

    public function create()
    {
        $data['company']=Company::where('office_type','head_office')->where('status', '1')->get();

        return view('financialyear.add',$data);
    }


    public function store(FinancialYearRequest $request)
    {
        $validator = \Validator::make($request->all(), [
            'financial_year_start_date' => 'required',
            'financial_year_end_date'   => 'required|after:financial_year_start_date',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data' => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $input               = $request->all();
        $input['company_id'] = \Auth::user()->company_id;
        $input['financial_year_start_date'] = date('Y-m-d', strtotime($request->financial_year_start_date));
        $input['financial_year_end_date']   = date('Y-m-d', strtotime($request->financial_year_end_date));

        $default_check = FinancialYear::where(['is_default' => '1','status' => '1'])->first();

        if (!$default_check) {
            $input['is_default'] = '1';
        }

        FinancialYear::create($input);

        $sessionSet = $this->setFinancialYearSession();
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Financial Year created successfully',
            ]);
        }

        return redirect('financialyear')->with('success','Financial Year created successfully.');
    }

   public function edit($id)
   {
      $financialyear   = FinancialYear::where('financialyearid', $id)->first();
    //   dd($financialyear );
      $data['company'] = Company::where('office_type','head_office')->where('status', '1')->get();

      if($financialyear =='') {
        return response()->json([
                'success' => false,
                'message' => 'Financial Year is Not Avaiable.',
            ]);
      }
      else
      {
        return view('financialyear.edit', compact('financialyear'));
      }
   }

   public function update($id,Request $request)
   {
        $validator = \Validator::make($request->all(), [
            'financial_year_start_date' => 'required',
            'financial_year_end_date'   => 'required|after:financial_year_start_date',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data' => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $input         = $request->all();
        $company_basic = FinancialYear::find($id);

        $input['financial_year_start_date'] = date('Y-m-d', strtotime($request->financial_year_start_date));
        $input['financial_year_end_date']   = date('Y-m-d', strtotime($request->financial_year_end_date));

        $company_basic->update($input);

        $sessionSet = $this->setFinancialYearSession();
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Financial Year updated successfully',
                'data' => $company_basic
            ]);
        }

        return redirect('financialyear')->with('success','Financial Year updated successfully');
   }
  public function delete(Request $request)
  {
        $financialyear = FinancialYear::find($request->id);

        if ($financialyear->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' =>    ['Default record can not be deleted.']
            ]);
        }

        $financialyear->delete();
        $Redirect = 'financialyear';
        $sessionSet = $this->setFinancialYearSession();

        return response()->json([
            'success'=>true,
            'message'=>['Deleted successfully'],
            'data'=>[
            'redirect'=>$Redirect,
            ]
        ]);
  }

   public function changeStatus(Request $request)
   {
       if ($request->ajax())
       {
           $data = array('status' => $request->status );
           $Update = FinancialYear::where('financialyearid', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Financial year status successfully change'],
                   'data'=>[
                       'redirect'=>'/financialyear/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
   }

   public function changedefault(Request $request)
   {
       if ($request->ajax())
       {
            $data  = array('is_default' => $request->status );
            $count = FinancialYear::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Financial year!'],
                    'data'    => []
                ]);
            }

           $Update = FinancialYear::where('financialyearid', '=', $request->id)->update($data);
           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Financial year default status successfully change'],
                   'data'=>[
                       'redirect'=>'/financialyear/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
   }
   public function  setFinancialYearSession()
    {
        $financial_year = FinancialYear::where(['company_id' => Auth::user()->company_id, 'status' => '1'])->latest()->first();

        Session::put('financial_year', $financial_year);

        $financialyear_id = Auth::user()->my_financial_year_id;
        $company_id       = Auth::user()->company_id;

        if (empty($financialyear_id) && $company_id) {
            $financialyear = FinancialYear::select('financialyearid')->where(['company_id' => $company_id, 'status' => '1'])
                ->orderBy('is_default', 'desc')
                ->first();

            $financialyear_id = $financialyear->financialyearid ?? '';
        }

        Session::put('user_financial_year_id', $financialyear_id);

        $financialyear = FinancialYear::select([
                'financialyearid',
                'financial_year_name',
                'company_id',
                'status',
                'is_default',
            ])
            ->where([
                'company_id' => $company_id,
                'status'     => '1'
            ])
            ->orderBy('is_default', 'desc')
            ->get();

        Session::put('financialyear', $financialyear);
    }
}
