<?php
ini_set('display_errors', 1);
require_once '../resources/base_path_include.php';
require_once $base_path_to_learning_resources . "includes/connect.php";
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';

//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 {
    $admission_number = (isset($postdata['admission_number']) && !empty($postdata['admission_number']))
        ? trim($postdata['admission_number']) : null;
    $institution_id = (isset($postdata['institution_id']) && !empty($postdata['institution_id']))
        ? trim($postdata['institution_id']) : null;
    $branch_id = (isset($postdata['branch_id']) && !empty($postdata['branch_id']))
        ? trim($postdata['branch_id']) : null;
    $password = isset($postdata['password']) ? $postdata['password'] : null;
    $portal = ['student'];

    // Validation
    if (is_null($admission_number) || is_null($institution_id) || is_null($branch_id)) {
        errorreturn('Admission number, institution ID, and branch ID are required.');
    }

    if (is_null($password) || $password === '') {
        errorreturn('Password is required.');
    }

    $ip = $_SERVER['REMOTE_ADDR'];
    $device = $_SERVER['REMOTE_ADDR'];
    $location = (isset($postdata['location']) && !empty($postdata['location'])) ? trim($postdata['location']) : null;
    $today = date('Y-m-d');

    // First get the workspace_id from institution
    $query = "SELECT workspace_id FROM institutions WHERE id = ?";
    $stmt = $conn_rjllearning->prepare($query);
    $stmt->execute([$institution_id]);
    $institution = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$institution) {
        errorreturn('Institution not found.');
    }

    $workspace_id = $institution['workspace_id'];

    // Establish specific database connection
    $conn_rjllearning_specific = getdbconnection($conn_rjllearning, $workspace_id);
    if (!$conn_rjllearning_specific) {
        errorreturn('Could not establish database connection.');
    }

    // Fetch student details 
    $query = "SELECT user_id FROM students 
              WHERE admission_number = ? AND institution_id = ? AND branch_id = ? AND can_activate = 1 AND status = 1 ";
    $stmt = $conn_rjllearning_specific->prepare($query);
    $stmt->execute([$admission_number, $institution_id, $branch_id]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$student) {
        errorreturn('Student not found or inactive.');
    }

    $userid = $student['user_id'];

    // Fetch user details from users table
    $query = "SELECT id, name, email, password, workspace_id, username, role, gender, institution_id FROM users 
              WHERE id = ? AND can_activate = 1 AND status = 1";
    $stmt = $conn_rjllearning->prepare($query);
    $stmt->execute([$userid]);
    $row = $stmt->fetchAll();

    if (count($row) == 1) {
        $userid = $row[0]['id'];
        $workspace_id = $row[0]['workspace_id'];
        $institution_id = $row[0]['institution_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'];

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

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

        // Store FCM token if provided
        if (isset($postdata['fcm_token'])) {
            $fcmToken = $postdata['fcm_token'];
            storeFCMToken($conn_rjllearning, $fcmToken, $userid);
        }

        $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,
                    "admission_number" => $admission_number
                ],
                $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" => $branch_id,
                "name" => $name,
                "email" => $email,
                "workspace_id" => $workspace_id,
                "username" => $created_by,
                "role" => $role,
                "class" => !empty($student_subject_info['class_info']['class_id']) ? $student_subject_info['class_info']['class_id'] : null,
                "section" => !empty($student_subject_info['section_info']['section_id']) ? $student_subject_info['section_info']['section_id'] : null,
                "admission_number" => $admission_number
            )
        );

        $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([
            $workspace_id,
            $created_by,
            $userid,
            $device,
            $ip,
            $location,
            time(),
            $today,
            $jwt,
            '1'
        ]);

        $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
        );

        successreturn($success_data);
    } else {
        errorreturn("Invalid credentials.");
    }
} catch (Exception $e) {
    die('ERROR: ' . $e->getMessage());
}