<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Auth, DB, Validator, File;
use Illuminate\Support\Str;

class AuthController extends Controller
{   
       
    /** login */
        public function login(Request $request){
            $rules = ['email' => 'required', 'password' => 'required'];
            $validator = Validator::make($request->all(), $rules);
            
            if($validator->fails())
                return response()->json(['status' => 422, 'message' => $validator->errors()]);
            
            $auth = auth()->attempt(['email' => $request->email, 'password' => $request->password]);
            
            if(!$auth){
                return response()->json(['status' => 401, 'message' => 'Invalid login details']);
            }else{
                $user = User::where('email', $request->email)->firstOrFail();
                
                if($user->status == 'active'){
                    $token = $user->createToken('auth_token')->plainTextToken;
                    $u = \Auth::user(); // get the authenticated User
                    $u->load('roles.permissions');
                    return response()->json(['status' => 200, 'message' => 'Login Successfully', 'token_type' => 'Bearer', 'access_token' => $token ,'permission' => $u]);
                }else{
                    return response()->json(['status' => 201, 'message' => 'This account has been inactive or deleted, please contact admin']);
                }
            }
        }
    /** login */
    
    /**
         * Mobile login (step 1): verify credentials, send OTP.
         * Returns a short-lived login_key used for OTP validation.
         */
        public function mobileLogin(Request $request)
        {
            $validator = Validator::make($request->all(), [
                'email' => 'required',
                'password' => 'required',
            ]);

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

            $auth = auth()->attempt(['email' => $request->email, 'password' => $request->password]);
            if (!$auth) {
                return response()->json(['status' => 401, 'message' => 'Invalid login details']);
            }

            $user = User::where('email', $request->email)->first();
            Auth::logout();

            if (!$user) {
                return response()->json(['status' => 401, 'message' => 'Invalid login details']);
            }

            if ($user->status !== 'active') {
                return response()->json(['status' => 201, 'message' => 'This account has been inactive or deleted, please contact admin']);
            }

            if (empty($user->contact_number)) {
                return response()->json(['status' => 422, 'message' => 'User does not have a registered mobile number']);
            }

            $otpResult = $this->sendOtpMsg91($user->contact_number);
            if (!$otpResult['ok']) {
                return response()->json([
                    'status' => 500,
                    'message' => 'Failed to send OTP, please try again',
                    'error' => $otpResult['error'] ?? null,
                ]);
            }

            $reqId = $otpResult['reqId'];

            $loginKey = (string) Str::uuid();
            cache()->put(
                'mobile_login:' . $loginKey,
                ['user_id' => $user->id, 'otp_request_id' => $reqId],
                now()->addMinutes(10)
            );

            return response()->json([
                'status' => 200,
                'message' => 'OTP sent to your registered mobile number',
                'login_key' => $loginKey,
                'otp_request_id' => $reqId,
            ]);
        }

        /**
         * Mobile login (step 2): validate OTP and issue Sanctum token.
         */
        public function mobileValidateOtp(Request $request)
        {
            $validator = Validator::make($request->all(), [
                'login_key' => 'required|string',
                'otp' => 'required|digits:4',
            ]);

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

            $payload = cache()->get('mobile_login:' . $request->login_key);
            if (!$payload || empty($payload['user_id']) || empty($payload['otp_request_id'])) {
                return response()->json(['status' => 401, 'message' => 'Login session expired, please login again']);
            }

            $isOtpValid = $this->verifyOtpMsg91($payload['otp_request_id'], $request->otp);
            if (!$isOtpValid) {
                return response()->json(['status' => 401, 'message' => 'Invalid OTP']);
            }

            $user = User::find($payload['user_id']); 
            if (!$user) {
                return response()->json(['status' => 401, 'message' => 'Login session invalid, please login again']);
            }
            if ($user->status !== 'active') {
                return response()->json(['status' => 201, 'message' => 'This account has been inactive or deleted, please contact admin']);
            }

            cache()->forget('mobile_login:' . $request->login_key);

            $token = $user->createToken('auth_token')->plainTextToken;
            $user->load('roles.permissions');

            return response()->json([
                'status' => 200,
                'message' => 'Login Successfully',
                'token_type' => 'Bearer',
                'access_token' => $token,
                'permission' => $user,
            ]);
        }

        private function normalizeIndianMobile($mobile)
        {
            $digits = preg_replace('/\D+/', '', (string) $mobile);
            if (!$digits) return null;

            // Common cases:
            // - "9876543210" -> "919876543210"
            // - "+91 98765 43210" -> "919876543210"
            // - "0919876543210" -> "919876543210"
            if (strlen($digits) === 10) {
                return '91' . $digits;
            }
            if (strlen($digits) === 12 && str_starts_with($digits, '91')) {
                return $digits;
            }
            if (strlen($digits) === 13 && str_starts_with($digits, '091')) {
                return substr($digits, 1);
            }

            // Fallback: send as-is (Msg91 will validate)
            return $digits;
        }

        private function sendOtpMsg91($mobile)
        {
            $authKey = env('MSG91_AUTH_KEY', '420299Ana879LrR689195eeP1');
            $widgetId = env('MSG91_WIDGET_ID', '356c716a4a31333034345830');

            $identifier = $this->normalizeIndianMobile($mobile);
            if (!$identifier) {
                return ['ok' => false, 'error' => 'Invalid mobile number format'];
            }

            $curl = curl_init();

            curl_setopt_array($curl, [
                CURLOPT_URL => "https://api.msg91.com/api/v5/widget/sendOtp",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_HTTPHEADER => [
                    "authkey: 420299Ana879LrR689195eeP1",
                    "content-type: application/json",
                ],
                CURLOPT_POSTFIELDS => json_encode([
                    "widgetId" => "356c716a4a31333034353830",
                    "identifier" => $identifier,
                ]),
            ]);

            $response = curl_exec($curl);
            $curlErrNo = curl_errno($curl);
            $curlErr = curl_error($curl);
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);

            if ($response === false || $curlErrNo) {
                return ['ok' => false, 'error' => 'cURL error: ' . ($curlErr ?: ('errno ' . $curlErrNo))];
            }

            $data = json_decode($response, true);
            if (!is_array($data)) {
                return ['ok' => false, 'error' => 'Invalid Msg91 response (HTTP ' . $httpCode . ')'];
            }

            if (isset($data['type']) && $data['type'] === 'success' && !empty($data['message'])) {
                return ['ok' => true, 'reqId' => $data['message']];
            }

            $msg = $data['message'] ?? ($data['errors'] ?? null);
            if (is_array($msg)) $msg = json_encode($msg);

            return ['ok' => false, 'error' => 'Msg91 error (HTTP ' . $httpCode . '): ' . ($msg ?: $response)];
        }

        private function verifyOtpMsg91($reqId, $otp)
        {
            $authKey = env('MSG91_AUTH_KEY', '420299Ana879LrR689195eeP1');
            $widgetId = env('MSG91_WIDGET_ID', '356c716a4a31333034345830');

            $curl = curl_init();

            curl_setopt_array($curl, [
                CURLOPT_URL => "https://api.msg91.com/api/v5/widget/verifyOtp",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_HTTPHEADER => [
                    "authkey: 420299Ana879LrR689195eeP1",
                    "content-type: application/json",
                ],
                CURLOPT_POSTFIELDS => json_encode([
                    "widgetId" => "356c716a4a31333034353830",
                    "reqId" => $reqId,
                    "otp" => $otp,
                ]),
            ]);

            $response = curl_exec($curl);
            $curlErrNo = curl_errno($curl);
            $curlErr = curl_error($curl);
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);

            if ($response === false || $curlErrNo) {
                return false;
            }

            $data = json_decode($response, true);
            if (is_array($data) && isset($data['type']) && $data['type'] === 'success') {
                return $data['message'];
            }

            return false;
        }
        
    /** logout */
        public function logout(Request $request){
            $request->user()->currentAccessToken()->delete();
            return response()->json(['status' => 200, 'message' => 'Logout Successfully']);
        }
    /** logout */
}
