<?php

// Display errors for debugging
ini_set('display_errors', 1);

// Include necessary files
require_once '../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources . "includes/connect.php"; // Database connection
require_once $base_path_to_learning_resources . "lib/function.php";
require_once $base_path_to_learning_resources . "lib/validate_api_signature.php";
require_once $base_path_to_learning_resources . "lib/validate_function.php";
require_once $base_path_to_learning . "user_management/authenticate.php";
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . "includes/specific_db_config.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "admin_api/modules/visitors_log/visitorlog_functions.php";

$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All fields are required.");
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Decode and validate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$name = $jwt_validate->data->name;

$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

// Validate institution_id and branch_id
$check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);

    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

$response = [];

$function_type = $postdata['function_type'];

// here we will check that function type should be visitor_stats else error

if ($function_type === "visitor_stats") {
    $min_date = isset($postdata['min_date']) ? $postdata['min_date'] : null;
    $max_date = isset($postdata['max_date']) ? $postdata['max_date'] : null;

    if (!$min_date || !$max_date || !strtotime($min_date) || !strtotime($max_date) || $min_date > $max_date) {
        errorreturn("Both min_date and max_date are required.");
    }

    if ($min_date == $max_date) {
        // Same day data only
        $result = [];
        $overall_total_visits = 0;
        $status_total = [
            'Pending' => 0,
            'Active' => 0,
            'Completed' => 0,
            'Denied' => 0
        ];

        $sql = "SELECT status, count(*) as visits 
                FROM visitors_log 
                WHERE institution_id = ? AND date = ?";

        if ($branch_id !== 'all') {
            $sql .= " AND branch_id = ?";
        }

        $sql .= " GROUP BY status";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $array_params = [$institution_id, $min_date];
        if ($branch_id !== 'all') {
            $array_params[] = $branch_id;
        }

        $stmt->execute($array_params);
        $daily_visitors = $stmt->fetchAll();

        $result[] = [
            'date' => $min_date,
            'statuses' => [
                'Pending' => 0,
                'Active' => 0,
                'Completed' => 0,
                'Denied' => 0
            ],
            'total_visits' => 0
        ];

        foreach ($daily_visitors as $visitors) {
            $status = intval($visitors['status']);
            $count_visits = intval($visitors['visits']);

            $overall_total_visits += $count_visits;
            $result[0]['total_visits'] += $count_visits;

            if ($status == 0) {
                $result[0]['statuses']['Pending'] += $count_visits;
                $status_total['Pending'] += $count_visits;
            } else if ($status == 1) {
                $result[0]['statuses']['Active'] += $count_visits;
                $status_total['Active'] += $count_visits;
            } else if ($status == 2) {
                $result[0]['statuses']['Completed'] += $count_visits;
                $status_total['Completed'] += $count_visits;
            } else if ($status == -1) {
                $result[0]['statuses']['Denied'] += $count_visits;
                $status_total['Denied'] += $count_visits;
            }
        }

        successreturn([
            'date_wise_info' => $result,
            'total_visitors' => $overall_total_visits,
            'stats_info' => $status_total
        ]);
    } else {
        // Calculate the date difference
        $date1 = new DateTime($min_date);
        $date2 = new DateTime($max_date);
        $interval = $date1->diff($date2);


        if ($interval->days <= 7) {
            // dateWise_visitors function
            $response = dateWise_visitors(
                $institution_id,
                $branch_id,
                $conn_rjllearning_specific,
                $min_date,
                $max_date
            );

        } else if ($interval->days <= 31) {
            // fetchWeeklyVisitors function
            $response = fetchWeeklyVisitors(
                $institution_id,
                $branch_id,
                $conn_rjllearning_specific,
                $min_date,
                $max_date
            );
        } else {
            // monthly data
            $response = fetchMonthlyVisitors(
                $institution_id,
                $branch_id,
                $conn_rjllearning_specific,
                $min_date,
                $max_date
            );
        }
        successreturn($response);
    }
} else {
    errorreturn("Invalid function_type");
}