<?php
ini_set('display_errors', 1);
//error_reporting(0);
require_once '../resources/base_path_include.php';
// should we not call header and ch
require_once $base_path_to_learning_resources . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'jwt/jwt_config.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . 'students_api/student_api_function/common_api_function.php';
require_once $base_path_to_learning . 'principal_api/principal_function/principal_function.php';

//fcm notification
require_once $base_path_to_learning . 'user_management/functions/fcm_token_function.php';
// require_once $base_path_to_resources . 'lib/cron_jobs/fcm_notifications.php';

//jwt token
use \Firebase\JWT\JWT;
use \Firebase\JWT\Key;
//aws image store
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = json_decode(file_get_contents("php://input"), true);
try {
    $username = (isset($postdata['username']) and !empty($postdata['username'])) ? trim($postdata['username']) : null;
    $branch_id = (isset($postdata['branch_id']) and !empty($postdata['branch_id'])) ? trim($postdata['branch_id']) : null;
    //$username = (isset($postdata['username']) and !empty($postdata['username'])) ? trim($postdata['username']) : null;
    $portal = (isset($postdata['portal']) and !empty($postdata['portal'])) ? ($postdata['portal']) : null;

    $password = $postdata['password'];
    $ip = $_SERVER['REMOTE_ADDR'];
    $device = $_SERVER['REMOTE_ADDR'];
    $location = (isset($postdata['location']) and !empty($postdata['location'])) ? trim($postdata['location']) : null;

    $today = date('Y-m-d'); // this format of date is not the one we are going to use
    $query = "SELECT id, name, email, password,workspace_id,username,role,gender,institution_id,branch_id FROM users WHERE username = ? and branch_id = ?  and can_activate = 1 and status = 1";
    $stmt = $conn_rjllearning->prepare($query);
    $stmt->execute(array($username,$branch_id));
    $row = $stmt->fetchAll();
    // print_r($row);die();
    if (count($row) == 1) {
        $userid = $row[0]['id'];
        $workspace_id = $row[0]['workspace_id'];
        $institution_id = $row[0]['institution_id'];
        $branch_id = $row[0]['branch_id'];
        $created_by = $row[0]['username'];
        $name = $row[0]['name'];
        $gender = $row[0]['gender'];
        $email = $row[0]['email'];
        $password2 = $row[0]['password'];
        $role = $row[0]['role'];

        // principal,student,teacher

        if (!password_verify($password, $password2)) {
            errorreturn('Invalid credentials.');
        }

        if (!in_array($role, $portal)) {
            errorreturn('You cannot access this portal.');
        }

        if (isset($postdata['fcm_token'])) {
            $fcmToken = $postdata['fcm_token']; // this must be in array
            storeFCMToken($conn_rjllearning, $fcmToken, $userid);
        }
        
        
         $merged_array =  array("name" => $name,"username" => $created_by,"gender" => $gender,"role" => $role);

        if ($role == 'student') {
            $institution_info = getInstitution($conn_rjllearning, $institution_id);
            $conn_rjllearning_specific = getdbconnection($conn_rjllearning, $workspace_id);

            if (!$conn_rjllearning_specific) {
                errorreturn('Access denied.');
            } else {
                $student_subject_info = getstudentsubject($conn_rjllearning_specific, $institution_id, $created_by);
                $merged_array = array_merge(
                    [
                        "student_id" => $userid,
                        "name" => $name,
                        "username" => $created_by,
                        "gender" => $gender,
                        "role" => $role
                    ],
                    $student_subject_info['student_info']
                );
                $site_setting = getPrintUISetting($conn_rjllearning_specific, $institution_id);
            }
        }
         $token = array(
                    "iat" => $issued_at,
                    "exp" => $expiration_time,
                    "iss" => $issuer,
                    "data" => array(
                        "institution_id" => $institution_id,
                        "id" => $userid,
                        "branch_id" => $student_subject_info['branch_info']['branch_id'],
                        "name" => $name,
                        "email" => $email,
                        "workspace_id" => $workspace_id,
                        "username" => $created_by,
                        "role" => $role,
                        "class" => $student_subject_info['class_info']['class_id'],
                        "section" =>$student_subject_info['section_info']['section_id'],
                    )
                );

        $jwt = JWT::encode($token, $key, 'HS256');
        $sql = "INSERT INTO user_log(workspace_id,username,userid,device,ip,location,time,date,jwttoken,status)
                    VALUES(?,?,?,?,?,?,?,?,?,?)";

        $res =  $conn_rjllearning->prepare($sql)->execute(array($workspace_id, $created_by, $userid, $device, $ip, $location, time(), $today, $jwt, '1'));
        
        if ($role == 'student') {
            $success_data = array(
                "success_msg" => "Successfully signed in",
                "jwt_token" => $jwt,
                "institution" => $institution_info,
                "site_setting" => $site_setting ?? null,
                "subject_info" => $student_subject_info['subject_info'] ?? null,
                "branch_info" => $student_subject_info['branch_info'] ?? null,
                "class_info" => $student_subject_info['class_info'] ?? null,
                "section_info" => $student_subject_info['section_info'] ?? null,
                "other_info" => $merged_array
            );
        } else {
            $success_data = array(
                "success_msg" => "Successfully signed in",
                "jwt_token" => $jwt,
                "other_info" => $merged_array
            );
        }

        successreturn($success_data);
    } else {
        errorreturn("Invalid credentials.");
    }
} catch (Exception $e) { // changed PDO exception to normal Exception here
    die('ERROR: ' . $e->getMessage());
}
