<?php

namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use App\Models\StaffModel;
use App\Models\StaffAttendanceModel;


class StaffAuthController extends ResourceController
{
    protected $format = 'json';
    protected $myLogger;
    protected $StaffModel;
    protected $StaffAttendanceModel;


    public function __construct()
    {
        helper('jwt_helper');
        helper('oauth_helper');
        $this->myLogger = \Config\Services::mylogger();
        $this->StaffModel = new StaffModel();
        $this->StaffAttendanceModel = new StaffAttendanceModel();

    }

    public function verifyStaffWithMobileNumber()
    {   
        try {

            $mobile = $this->request->getJSON()->mobile;
         
            $StaffData = $this->StaffModel->where('mobile', $mobile)->where('is_active', 1)->first();

           
            if (isset($StaffData['id'])) 
            {
                if (env('CI_ENVIRONMENT') === 'development') {
                    $otp = 123456; // Static OTP for development
                } else {
                    $otp = random_int(100000, 999999);
                }

                $update = $this->StaffModel->where('mobile', $mobile)->where('is_active', 1)->set(['email_otp' => $otp])->update();
                    
                if ($update) {

                    //  Skip SMS in development
                    if (env('CI_ENVIRONMENT') === 'development') {
                        $result = ['Staff_verification' => true, 'message' => "Verified Successfully (DEV MODE - OTP: 123456)" ];
                        return $this->respond(['status' => 'success','code'   => 200,'data'   => $result], 200);
                    }
    
                    $SMSResult = sendOtpSms($mobile,$otp);
                   
                    if ($SMSResult['status'] == 'success') {
                        $result = ['Staff_verification' => true, 'message' => "Verified Successfully"];
                        return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
                    } else {
                        $result = ['Staff_verification' => false, 'message' => "Mail sending failed , try again"];
                        return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
                    }
                } else {
                    $result = ['Staff_verification' => false, 'message' => "Verification failed , try again"];
                    return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
                }

            } else {
               
                $result = ['Staff_verification' => false , 'message' => "User not found"];
                return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);

            }
        } catch (\Throwable $th) {
           
            return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
        }
    }

    public function verifyStaffWithEmailId()
    {   
        try {

            $email = $this->request->getJSON()->email;

            $StaffData = $this->StaffModel->where('email', $email)->where('is_active', 1)->first();

            if (isset($StaffData['id'])) {

                if (env('CI_ENVIRONMENT') === 'development') {
                    $otp = 123456; // Static OTP for development
                } else {
                    $otp = random_int(100000, 999999);
                }

                $update = $this->StaffModel->where('email', $email)->where('is_active', 1)->set(['email_otp' => $otp])->update();
                    
                if ($update) {

                    //  Skip SMS in development
                    if (env('CI_ENVIRONMENT') === 'development') {
                        $result = ['Staff_verification' => true, 'message' => "Verified Successfully (DEV MODE - OTP: 123456)" ];
                        return $this->respond(['status' => 'success','code'   => 200,'data'   => $result], 200);
                    }
    
                    $EmailResult = trigger_email('login_otp',['email'=>$email, 'name'=>$StaffData['name'], 'otp'=>$otp, ]);
                   
                    if ($EmailResult['status'] == 'success') {
                        $result = ['Staff_verification' => true, 'message' => "Verified Successfully"];
                        return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result], 200);
                    } else {
                        $result = ['Staff_verification' => false, 'message' => "Mail sending failed , try again"];
                        return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
                    }
                } else {
                    $result = ['Staff_verification' => false, 'message' => "Verification failed , try again"];
                    return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
                }

            } else {
                $result = ['Staff_verification' => false, 'message' => "User not found"];
                return $this->respond(['status' => 'failed', 'code' => 404, 'data' => $result], 200);
            }

        } catch (\Throwable $th) {
            return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $th], 500);
        }
    }

    public function getVerifiedStaffData()
    {   
        try {
        
            $mobile = isset($this->request->getJSON()->mobile) ? $this->request->getJSON()->mobile : null;
            $email = isset($this->request->getJSON()->email) ? $this->request->getJSON()->email : null;
            $otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null;


            if (isset($mobile)) 
            {
                $StaffData = $this->StaffModel->where('mobile', $mobile)->where('is_active', 1)->where('email_otp', $otp)->first();

            } else {
                $StaffData = $this->StaffModel->where('email', $email)->where('email_otp', $otp)->where('is_active', 1)->first();
            }   
            

            if ($StaffData && isset($this->request->getJSON()->otp) ) {
            
                $this->StaffModel->where('id', $StaffData['id'])->where('email_otp', $otp)->where('is_active', 1)->set(['email_otp'=>null])->update();


                // Attendance check or insert
                $today = date('Y-m-d');

                $existingAttendance = $this->StaffAttendanceModel->where('staff_id', $StaffData['id'])->where('DATE(login_datetime)', $today)->first();

                if (!$existingAttendance) {
                    // New login for today
                    $this->StaffAttendanceModel->insert(['staff_id' => $StaffData['id'],'login_datetime' => date('Y-m-d H:i:s'),'manager_id'=>$StaffData['manager_id']]);
                    $lastLoginTime = date('Y-m-d H:i:s');
                } else {
                    // Already logged in today, reuse last login time
                    $lastLoginTime = $existingAttendance['login_datetime'];
                }

                // Add last login info to JWT
                $StaffData['last_login_datetime'] = $lastLoginTime;
                
                $result = generateJWT($StaffData);

                return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);

            } else {
                
                return $this->respond(['status' => 'failed','code' => 404,'data' => 'Please try again'],200);
            }

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed','code' => 500,'data' =>[], 'error' => $e->getMessage()],500);
        }
    }


    public function logout()
    {
        
        $header = $this->request->getHeaderLine('Authorization'); // Get the full header

        if (!$header || !preg_match('/Bearer\s(\S+)/', $header, $matches)) {
            return service('response')->setJSON(['status' => 401, 'message' => 'Token required'])->setStatusCode(401);
        }

        $decodedToken = validateJWT($matches[1]);

        $userId = $decodedToken['data']->id ?? null;
        $lastLogin = $decodedToken['data']->last_login_datetime ?? null;

        if ($userId && $lastLogin) {

            $lastLoginDate = date('Y-m-d', strtotime($lastLogin));
            $todayDate = date('Y-m-d');

            $attendanceModel = new \App\Models\StaffAttendanceModel();

            // Find  attendance record 
            $attendance = $attendanceModel
                ->where('staff_id', $userId)
                ->where('DATE(login_datetime)', $lastLoginDate)
                ->first();
                
            if ($attendance) {
                $attendanceModel->update($attendance['id'], [
                    'logout_datetime' => date('Y-m-d H:i:s')
                ]);
            }

            log_message('info', sprintf(
                'logout triggered for Staff ID: %s. Previous login date: %s, Current date: %s, Logout time updated at: %s',
                $userId,
                $lastLoginDate,
                $todayDate,
                date('Y-m-d H:i:s')
            ));

        }
    
        return $this->respond([
            'status'  => 200,
            'message' => 'Logout successful'
        ], 200);
    }





  



}
