<?php

namespace App\Http\Controllers\Admin;

use App\Events\RequestManual;
use App\Http\Controllers\Controller;
use App\Helpers\Helper;
use App\Models\AttendanceRequest;
use App\Models\HolidayReport;
use App\Months;
use App\Salary;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Redirect;
use Validator;
use Session;

class ApproveManualController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (session('employee_sidebar') == 'Employee') {
            return Redirect::route('employee_category.index');
        } 
        if (session('password_entered')) {
            Session::flush();
            return redirect('/');
        }

        Helper::cache_all();
        if(request()->ajax()){
            return datatables()->of( Helper::cache_approve_manual() )
                ->addColumn('view', function($data){
                    $button2 = '<button type="button" name="view" id="'.$data->idx.'" class="view btn btn-info btn-sm mr-2">Edit</button>';
                    return $button2;
                })
                ->addColumn('chkbox', function($data){
                    $button = '
                    <div class="icheck-primary">
                        <input type="checkbox" name="checkbox_id" id="checkbox_id'.$data->idx.'" class="chkbox" value="'.$data->idx.'">
                        <label for="checkbox_id'.$data->idx.'"></label>
                    </div>';
                    return $button;
                })
                ->rawColumns(['chkbox', 'view'])
                ->make(true);
        }
        
        return view ('admin.approve_manual.index');
    }

    // public function indexA()
    // {
    //     Helper::cache_all();
    //     if(request()->ajax()){
    //         return datatables()->of( Helper::cache_approve_manual_user() )
    //             ->addColumn('action', function($data){
    //                 // $button3 = '<a href="" id="edit" > <button type="btn" name="action" id="" class="btn btn-info btn-sm" >Edit</button> </a>';
    //                 $button3 = '<button type="btn" name="edit" id="'.$data->idx.'" class="edit btn btn-info btn-sm" >Edit</button>';
    //                 return $button3;
    //             })
    //             ->rawColumns(['action'])
    //             ->make(true);
    //     }
        
    //     return view ('admin.approve_manual.index');
    // }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */




    public function store(Request $request, $id)
    {
        $rules = array(
            'id'    =>  'required',   //ID IS REQUIRED
            'date' => 'required',
            'category' => 'required',
            'duration' => 'required',
            'amount' => 'required',
            'status' => 'required'
        );
        $error = Validator::make($request->all(), $rules);   //Validator 
        if($error->fails())                              //if errors is fails mag reresponse errors sa lahat
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }
        // $user = auth()->user();
        $form_data = array(   //Form data
            // 'approved_id'   =>  $user->id,
            'date' => $request->status,
            'category' => $request->status,
            'duration' => $request->status,
            'amount' => $request->status,
            'status' => $request->status
            
        );
        AttendanceRequest::create($form_data);

        return response()->json(['success' => 'Data Added successfully.']);
    }



    public function update(Request $request, AttendanceRequest $id)
    {
        $rules = array(
            'id'    =>  'required',   //ID IS REQUIRED
            'date' => 'required',
            'category' => 'required',
            'duration' => 'required',
            'amount' => 'required',
            'status' => 'required'
        );
        $error = Validator::make($request->all(), $rules);   //Validator 
        if($error->fails())                              //if errors is fails mag reresponse errors sa lahat
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }
        // $user = auth()->user();
        $form_data = array(   //Form data
            // 'approved_id'   =>  $user->id,
            'date' => $request->status,
            'category' => $request->status,
            'duration' => $request->status,
            'amount' => $request->status,
            'status' => $request->status
            
        );
        AttendanceRequest::whereIn($request->hidden_id)->update($form_data);

        return response()->json(['success' => 'Data Added updated.']);
    }







    // public function store(Request $request)
    // {
    //     if (session('employee_sidebar') == 'Employee') {
    //         return Redirect::route('employee_category.index');
    //     } 
    //     if (session('password_entered')) {
    //         Session::flush();
    //         return redirect('/');
    //     }
        
    //     $month2 = Months::get();
    //     if (!$month2->isEmpty()) {
    //         $month = Months::latest()->first();
    //         if ($month->status != 'Approved') {
    //             return response()->json(['payroll' => 'Sorry, Payroll already generated!']);
    //         }
    //     }

    //     $rules = array(
    //         'id'    =>  'required',   //ID IS REQUIRED
    //     );
    //     $error = Validator::make($request->all(), $rules);   //Validator 
    //     if($error->fails())                              //if errors is fails mag reresponse errors sa lahat
    //     {
    //         return response()->json(['errors' => $error->errors()->all()]);
    //     }
        
    //     $user = auth()->user();
    //     $form_data = array(   //Form data
    //         'approved_id'   =>  $user->id,
    //         'status'        =>  $request->status,
    //     );

    //     $id_list = $request->id;
    //     if (is_array($id_list) == false) {
    //         $datas = DB::table('users')
    //             ->select( 'ar.user_id AS user_id', 'ar.date',  'ar.category', 'ar.amount') //select the user data.
    //             ->leftJoin('attendance_requests AS ar', 'users.id', '=', 'ar.user_id') 
    //             ->where('ar.id', '=' , $id_list)  
    //             ->get();
    //             $user_id     = $datas[0]->user_id;
    //             $date        = $datas[0]->date;
    //             $category    = $datas[0]->category;
    //             $amount      = $datas[0]->amount;

            
    //         if ($category == 'Overtime') {
    //             $into = 'overtime';
    //         } 
    //         else if ($category == 'Extra Day') {
    //             $into = 'extra_day';
    //         }
    //         else if ($category == 'Holiday') {
    //             $into = 'holiday';
    //         }

    //         // Deduction
    //         else if ($category == 'Tardy') {
    //             $into = 'tardy';
    //         }
    //         else if ($category == 'Undertime') {
    //             $into = 'undertime';
    //         }

    //         // Absent is for Misout employee only pag hindi nag input si employee ng datr sa time out
    //         else if ($category == 'Absent') {
    //             $into = 'absent';
    //         }

    //         if ($request->status == "Approved") {
    //             Salary::whereUserId( $user_id )->increment( $into , $amount );

    //             if ($datas[0]->category == 'Holiday') {
    //                 $data = DB::table('holidays')
    //                     ->select( 'holidays.id', 'holidays.date', 'holidays.name', 'holidays.type')
    //                     ->where('holidays.date', '=' , $date)
    //                     ->get();

    //                 $form_holiday = array(
    //                     'user_id'     =>  $user_id,
    //                     'approved_id' =>  auth()->user()->id,
    //                     'holiday_id'  =>  $data[0]->id,
    //                     'date'        =>  $date,
    //                     'name'        =>  $data[0]->name,
    //                     'type'        =>  $data[0]->type
    //                 );
    //                 HolidayReport::create($form_holiday);
    //             }
    //         }
    //         AttendanceRequest::where('id', '=', $id_list)->update($form_data);
    //     } 
    //     else {
    //         $count = count($id_list);
    //         for ($i=0; $i < $count; $i++) { 
    //             // PARA MAKUHA UNAHAN
    //             $firstArr = reset($id_list);
    
    //             // GET DATA FROM DB TO RESET AMOUNTS*****  
    //             $datas = DB::table('users')
    //                 ->select( 'ar.user_id AS user_id', 'ar.date', 'ar.category', 'ar.amount')
    //                 ->leftJoin('attendance_requests AS ar', 'users.id', '=', 'ar.user_id')
    //                 ->where('ar.id', '=' , $id_list)
    //                 ->get();
    //             $user_id     = $datas[0]->user_id;
    //             $date        = $datas[0]->date;
    //             $category    = $datas[0]->category;
    //             $amount      = $datas[0]->amount;
    
                
    //             if ($category == 'Overtime') {
    //                 $into = 'overtime';
    //             } 
    //             else if ($category == 'Extra Day') {
    //                 $into = 'extra_day';
    //             }
    //             else if ($category == 'Holiday') {
    //                 $into = 'holiday';
    //             }
                
    //             // Deduction
    //             else if ($category == 'Tardy') {
    //                 $into = 'tardy';
    //             }
    //             else if ($category == 'Undertime') {
    //                 $into = 'undertime';
    //             }
    //             if ($request->status == "Approved") {
    //                 Salary::whereUserId( $user_id )->increment( $into , $amount );

    //                 if ($datas[0]->category == 'Holiday') {
    //                     $data = DB::table('holidays')
    //                         ->select( 'holidays.id', 'holidays.date', 'holidays.name', 'holidays.type')
    //                         ->where('holidays.date', '=' , $date)
    //                         ->get();

    //                     $form_holiday = array(
    //                         'user_id'     =>  $user_id,
    //                         'approved_id' =>  auth()->user()->id,
    //                         'holiday_id'  =>  $data[0]->id,
    //                         'date'        =>  $date,
    //                         'name'        =>  $data[0]->name,
    //                         'type'        =>  $data[0]->type
    //                     );
    //                     HolidayReport::create($form_holiday);
    //                 }
    //             }
    //             AttendanceRequest::where('id', '=', $firstArr)->update($form_data);
    //             // TO DELETE FIRST ARRAY ID***
    //             if (($key = array_search($firstArr, $id_list)) !== false) {
    //                 unset($id_list[$key]);
    //             } 
    //         }
    //     }

    //     Helper::cache_all();

    //     $reporting_to = auth()->user()->id;
    //     $helper = new Helper();
    //     event(new RequestManual($helper->check_count_timetable($reporting_to)['sum_count_timetable'], $helper->check_count_timetable($reporting_to)['count_manual'], $reporting_to));
        
    //     $text = "Success";
    //     return response()->json(['success' => $text]);
    // }



    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = DB::table('users')
            ->select('users.emp_no', 'users.name', 'users.picture', 'ar.date', 'ar.category', 'ar.duration', 'ar.amount', 'ar.status', 'ar.request_type', 'ar.id AS idx')
            ->leftJoin('attendance_requests AS ar', 'users.id', '=', 'ar.user_id')
            ->where([
                ['ar.status', '=', 'Request'],
                ['ar.request_type', '=', 'Manual'], 
                ['ar.id', '=', $id],
                // ['users.reporting_to', '=', $id],
            ])
            ->get();
        return response(['data' => $data]);
    }





    public function edit_user($id)
    {
        if(request()->ajax()){
            $data = DB::table('users')
            ->select('users.emp_no', 'users.name', 'users.picture', 'ar.date', 'ar.category', 'ar.duration', 'ar.amount', 'ar.status', 'ar.request_type', 'ar.id AS idx')
            ->leftJoin('attendance_requests AS ar', 'users.id', '=', 'ar.user_id')
            ->where([
                ['ar.status', '=', 'Request'],
                ['ar.request_type', '=', 'Manual'], 
                ['ar.id', '=', $id],
            ])
            ->get();
        return response(['data' => $data]);
        }
    }



    // public function update(Request $request, Sample_data $sample_data)
    // {
    //     $rules = array(
    //         'first_name'        =>  'required',
    //         'last_name'         =>  'required'
    //     );

    //     $error = Validator::make($request->all(), $rules);

    //     if($error->fails())
    //     {
    //         return response()->json(['errors' => $error->errors()->all()]);
    //     }

    //     $form_data = array(
    //         'first_name'    =>  $request->first_name,
    //         'last_name'     =>  $request->last_name
    //     );

    //     Sample_data::whereId($request->hidden_id)->update($form_data);

    //     return response()->json(['success' => 'Data is successfully updated']);

    // }






    // public function edit2($id)
    // {
    //    if(request()-ajax()){
    //     $data = DB::table('users')
    //     ->select('users.emp_no', 'users.name', 'users.picture', 'ar.date', 'ar.category', 'ar.duration', 'ar.amount', 'ar.status', 'ar.request_type', 'ar.id AS idx')
    //     ->leftJoin('attendance_requests AS ar', 'users.id', '=', 'ar.user_id')
    //     ->where([
    //         ['ar.status', '=', 'Request'],
    //         ['ar.request_type', '=', 'Manual'], 
    //         ['ar.id', '=', $id],
    //         // ['users.reporting_to', '=', $id],
    //     ])
    //     ->get();
    //    }
    // }

}
