<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Models\Employee;
use App\Models\EmployeeEducation;
use App\Models\EmployeeDocument;
use App\Models\EducationLevel;
use App\Models\DocumentType;
use App\Models\Grade;
use App\Models\Designation;
use App\Models\PayrollHead;
use App\Models\GradeStructure;
use App\Models\PayrollStructure;
use App\Models\PayrollStructureDetail;

class PayrollStructureController extends Controller
{
    public function index()
    {
        $data['title'] = "Employee Payroll Structure";
        $data['all']   = PayrollStructure::with(['psHead','employee','designationName.designation','grade','gradeHead.head'])->where('type','!=',4)->get();
        return view('admin.payroll_structure.index',$data);
    }
    
    public function psUpdate($id)
    {
        $data['title'] = "Payroll Structure Update";
        $data['single'] = PayrollStructure::with(['employee','designationName.designation','grade','psHead.head'])->find($id);
        $data['head'] = GradeStructure::with(['head'])->where('grade_id',$data['single']->grade_id)->get();
        return view('admin.payroll_structure.edit',$data);
    }

    
    public function update(Request $request, $id)
    {
        $user_id = \Auth::user()->id;
        $this->validate($request,[
            'amount.*' => 'required'
        ],
        ['required' => 'Amount Field is Required.']);

        PayrollStructureDetail::where('structure_id',$id)->delete();
        $input = $request->all();
        $condition = $input['head'];
        foreach ($condition as $key => $condition) {
            $psd = new PayrollStructureDetail;
            $psd->structure_id = $id;
            $psd->head_id = $input['head'][$key];
            $psd->amount = $input['amount'][$key];
            $psd->added_by = $user_id ;
            $psd->save();
        }

        return redirect('admin/payroll_structure')->with('msg','Data Update Successful!');
    }

    
    public function destroy($id)
    {
        PayrollStructure::whereId($id)->delete();
        return redirect('admin/payroll_structure')->with('msg','Successfully Deleted!');
    }
    public function statusUpdate($id)
    {

        $user_id = \Auth::user()->id;
        $ph_info = PayrollStructure::find($id);
        if($ph_info->status == 0){
            $ph_info->status = 1;
            $status = 'published';
        }else{
            $ph_info->status = 0;
            $status = 'unpublished';
        }
        $ph_info->update();

    }
}
