<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\PersonalInformation;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;
use Illuminate\Support\Str;

class PersonalInformationController extends Controller
{
    
    /**
     * Display a listing of the resource.
     */
    // public function index(Request $request)
    // {
    //     //
    //     $keyword = $request->input('keyword', '');
    //     $perPage = $request->input('per_page',PHP_INT_MAX);
    //     $sortBy = $request->input('sortBy', '');
    //     $sortType = $request->input('sortType', '');
    //     $data = PersonalInformation::where(function ($query) use ($keyword) {
    //         $keyword = str_replace(" ", "%", $keyword);
    //         $query->where('name', 'like', '%' . $keyword . '%');
    //     });

    //     if (!empty($sortBy) && !empty($sortType)) {
    //         $data = $data->orderBy($sortBy, $sortType);
    //     }

    //     $data = $data->paginate($perPage);
    //     return response()->json($data);
    // }

    public function show(string $id)
    {
        try {
            $id = Crypt::decrypt($id);
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
            $id = $id;
        }

        $data = Employee::with([
            'personal_information',
            'personal_information.citizenship',
            'personal_information.civil_status',
            'personal_information.religion'
        ])
        ->select(DB::raw("CONCAT(firstname, ' ', lastname) as full_name"), 'employees.*')
        ->where('employees.employee_id', '=', $id)->first();
        
        return response()->json($data);
    }
    
    public function store(Request $request, string $employee_id)
    {
        try {
            $employee_id = Crypt::decrypt($employee_id);
            $request['employee_id'] = $employee_id;
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
            $employee_id = $employee_id;
        }
        
        $employeeExists = PersonalInformation::where('employee_id', $employee_id)->exists();
        
        $validator = Validator::make($request->all(), [
            // 'passport_id' => [
            //     'required',
            //     'min:1',
            // ],
        ]);
        
        // dd($employeeExists);   

        if($employeeExists){
            $data = PersonalInformation::where('employee_id', $employee_id)->first();
            $employee = Employee::where('employee_id', $employee_id)->first();

            if (!$data) {
                return response()->json(['messages' => 'No data found.'], 404);
            }

            /** If validation fails return with error message */
            if ($validator->fails()) {
                $errors = $validator->errors();
                $first = $errors->getMessages();
                return response()->json([
                    'status'  => false,
                    'message' => (reset($first))[0],
                    'errors'  => $errors
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            DB::connection()->beginTransaction();

            try {

                if ($employee) {
                    $employee->mobile = $request->contact_number_one;
                    $employee->save();
                }

                $data->fill($request->all());
                $data->save();

                $data->touch();

                DB::connection()->commit();

                return response()->json([
                    'message' => 'Record Successfully updated!',
                    'status' => 'success',
                    'data' => $data,
                ], 201);

            } catch (Throwable $e) {
                DB::connection()->rollback();
                return response()->json([
                    'status'  => false,
                    'message' => 'Unable to process request. Please try again.',
                    'data'    => $e->getMessage()
                ]);
            }
        } else {
            /** If validation fails return with error message */
            if ($validator->fails()) {
                $errors = $validator->errors();
                $first = $errors->getMessages();
                return response()->json([
                    'status'  => false,
                    'message' => (reset($first))[0],
                    'errors'  => $errors
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            DB::connection()->beginTransaction();

            try {

                $data = PersonalInformation::create($request->all());

                DB::connection()->commit();

                return response()->json([
                    'message' => 'Record Successfully added!',
                    'status' => 'success',
                ],201);

            } catch (Throwable $e) {
                DB::connection()->rollback();
                return response()->json([
                    'status'  => false,
                    'message' => 'Unable to process request. Please try again.',
                    'data'    => $e->getMessage()
                ]);
            }
        }
    }
}
