<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Helpers\HelperController;
use App\Http\Resources\APiMaterialsResource;
use App\Http\Resources\ClerksResource;
use App\Models\Location_clerks;
use App\Models\Stock_take;
use App\Models\Stock_take_material;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    /**
     * Method login
     *
     * @param Request $request [explicite description]
     *
     * @return void
     */
    public function login(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'email' => ['required', 'email', 'max:191'],
                'password' => ['required']
            ]);

            if ($validator->fails()) {
                return response()->json(['errors' => $validator->errors()], 404);
            }

            $user = User::where('email', $request->email)->first();
            if ($user) {
                //check password
                if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
                    $res = HelperController::get_token();
                    $api_token = $res->message;
                    $user = User::where('email', $request->email)->first();
                    //check user role
                    $user->update(['last_login' => now(), 'token' => $api_token]);
                    $token = $user->createToken('authentictoken')->plainTextToken;
                    $result = [
                        'status' => 200,
                        'token' => $token,
                        'user_details' => $user
                    ];
                    return response()->json($result, 200);
                } else {
                    $result = [
                        'status' => 404,
                        'message' => 'Invalid Password'
                    ];
                    return response()->json($result, 404);
                }
            } else {
                $result = [
                    'status' => 404,
                    'message' => 'User account does not exist'
                ];
                return response()->json($result, 404);
            }
        } catch (\Throwable $e) {
            $response = [
                'message' => 'Error: ' . $e->getMessage(),
                'status' => 500
            ];
            return response()->json($response, 500);
        }
    }
    /**
     * Method logout
     *
     * @return void
     */
    public function logout()
    {
        try {
            Auth::user()->tokens()->delete();
            $result = [
                'status' => 200,
                'message' => 'Logout successful!',
            ];
            return response()->json($result, 200);
        } catch (\Throwable $th) {
            $result = [
                'status' => 500,
                'message' => $th->getMessage(),
            ];
            return response()->json($result, 500);
        }
    }
    /**
     * Method user_profile
     *
     * @return void
     */
    public function user_profile()
    {
        try {
            $user = Auth::user();
            $result = [
                'status' => 200,
                'user_data' => $user,
            ];
            return response()->json($result, 200);
        } catch (\Throwable $th) {
            $result = [
                'status' => 500,
                'user_data' => $th->getMessage(),
            ];
            return response()->json($result, 500);
        }
    }
    /**
     * Method locations
     *
     * @return void
     */
    public function locations()
    {
        try {
            $user = Auth::user();
            $locations = Location_clerks::where([['user_id', $user->id], ['status', 'active']])->with(['locations', 'stock_takes'])->get();
            $result = [
                'status' => 200,
                'user_locations' => ClerksResource::collection($locations),
            ];
            return response()->json($result, 200);
        } catch (\Throwable $th) {
            $result = [
                'status' => 500,
                'user_locations' => $th->getMessage(),
            ];
            return response()->json($result, 500);
        }
    }

    public function plant()
    {
        try {
            $user = Auth::user();
            $plant = Location_clerks::where([['user_id', $user->id], ['status', 'active']])->whereNotNull('plant_code')->with(['plants'])->first();
            $result = [
                'status' => 200,
                'user_plant' => $plant,
            ];
            return response()->json($result, 200);
        } catch (\Throwable $th) {
            $result = [
                'status' => 500,
                'user_plant' => $th->getMessage(),
            ];
            return response()->json($result, 500);
        }
    }

    /**
     * Method stock_take_materials
     *
     * @param $location_code $location_code [explicite description]
     *
     * @return void
     */
    public function stock_take_materials($location_code)
    {
        try {
            $user = Auth::user();
            $token = $user->token;
            $stock = Location_clerks::where([['location_code', $location_code], ['status', 'active']])->first();

            $stock_take = Stock_take::where('id', $stock->stock_take_id)->first();

            if ($stock_take) {
                if (!is_null($stock_take->doc_no)) {

                    //get count result of team A and B.
                    //check if null
                    $team_A_result = Stock_take_material::where('stock_take_id', $stock_take->id)->get()->sum('team_A_result');
                    $team_B_result = Stock_take_material::where('stock_take_id', $stock_take->id)->get()->sum('team_B_result');

                    if($team_A_result == 0 || $team_B_result == 0){

                        //getting all the materials
                        $materials = Stock_take_material::where('stock_take_id', $stock_take->id )->get();

                    } else{

                        //getting all the materials with variance for recounting
                        $materials = Stock_take_material::where([['stock_take_id', $stock_take->id], ['local_variance', '!=', 0]])->get();
                        
                    }


                    if ($materials) {
                        //dd($url);
                        $result = [
                            'materials' => APiMaterialsResource::collection($materials),
                            'stock_take_id' => $stock_take->id,
                            'plant_code' => $stock->plant_code,
                            'location_code' => $location_code,
                            'status' => 200,
                        ];
                    } else {
                        $result = [
                            'status' => 501,
                            'message' => 'No materials loaded'
                        ];
                    }
                } else {
                    $result = [
                        'status' => 501,
                        'message' => 'No materials loaded'
                    ];
                }
            } else {
                $result = [
                    'status' => 501,
                    'message' => 'Stock take for this location has not been initiated'
                ];
            }

            return response()->json($result, 200);
        } catch (\Throwable $th) {
            $result = [
                'res' => $th->getMessage(),
                'status' => 200,
            ];
            return response()->json($result, 200);
        }
    }
}