<?php
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');
ini_set('max_execution_time', 0);
ini_set('allow_url_fopen', '1');

date_default_timezone_set('Asia/Kolkata');

require_once '../../../../../resources/base_path_include.php';
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_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';

require_once $base_path_to_learning . 'user_management/authenticate.php';

//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';


require_once $base_path_to_learning . 'user_management/faculty/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';

require_once $base_path_to_learning_resources . "lib/function.php";
require_once $base_path_to_learning_resources . 'lib/common_modules/import/student_data/function.php';


$institution_id = "34";
$userid = "30";
$role = "superadmin";
$workspace_id = "19";
$username = "kunalpadam9988@gmail.com";

// Validate user and get specific DB
$specific_db_name = validateUserAccess(
    $conn_rjllearning,
    $userid,
    $role,
    $workspace_id,
    ["superadmin", "admin", "principal", "teacher"],
    null
);

if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

// Check academic session
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academic_id) {
    errorreturn("Access denied. Academic session not active.");
}

$conn_rjllearning_specific->beginTransaction();

$logTime = date("Y-m-d_H-i-s");
$logPath = __DIR__ . "/logs/attendance_import_$logTime"; // Make sure this folder exists

$logSuccess = "$logPath/success.log";
$logSkipped = "$logPath/skipped.log";
$logError = "$logPath/errors.log";
$logProgress = "$logPath/progress.log";

@mkdir($logPath, 0777, true); // Ensure log directory exists

try {
    // $conn_rjllearning_specific->beginTransaction();

    $studentStmt = $conn_rjllearning_specific->prepare("
        SELECT id, class_id, section_id 
        FROM students 
        WHERE admission_number = ? AND institution_id = ? AND branch_id = ?
    ");

    $checkStmt = $conn_rjllearning_specific->prepare("
        SELECT id 
        FROM student_attendance_daywise 
        WHERE student_id = ? AND date = ?
    ");

    $insertStmt = $conn_rjllearning_specific->prepare("
        INSERT INTO student_attendance_daywise 
        (institution_id, branch_id, student_id, academic_id, class_id, section_id, value, date, added_by, last_updated_by, time_created, last_updated_time)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $fetchOffline = $conn_rjllearning_specific->query("
        SELECT date, uniqueadm, value, branch, class, section 
        FROM attendance_offline
    ");
    
    $rows = $fetchOffline->fetchAll(PDO::FETCH_ASSOC);
    $total = count($rows);
    $processed = 0;
    $successCount = 0;
    $skippedCount = 0;

    $studentCache = [];

    foreach ($rows as $row) {
        $processed++;
        $admission_no = trim($row['uniqueadm']);
        $branch_name = trim($row['branch']);
        $date = trim($row['date']);
        $value = trim($row['value']);

        // Get branch ID
        $branch_id = getBranchId($conn_rjllearning_specific, $institution_id, $branch_name);
        if (!$branch_id) {
            file_put_contents($logSkipped, "[$processed/$total] Branch not found: $branch_name\n", FILE_APPEND);
            $skippedCount++;
            continue;
        }

        // Get student (cached)
        $studentKey = $admission_no . "|" . $branch_id;
        if (!isset($studentCache[$studentKey])) {
            $studentStmt->execute([$admission_no, $institution_id, $branch_id]);
            $student = $studentStmt->fetch(PDO::FETCH_ASSOC);
            if (!$student) {
                file_put_contents($logSkipped, "[$processed/$total] Student not found: $admission_no in branch $branch_name\n", FILE_APPEND);
                $skippedCount++;
                continue;
            }
            $studentCache[$studentKey] = $student;
        } else {
            $student = $studentCache[$studentKey];
        }

        $student_id = $student['id'];
        $class_id = $student['class_id'];
        $section_id = $student['section_id'];

        // Check for duplicates
        $checkStmt->execute([$student_id, $date]);
        if ($checkStmt->fetch()) {
            file_put_contents($logSkipped, "[$processed/$total] Duplicate attendance skipped: $admission_no on $date\n", FILE_APPEND);
            $skippedCount++;
            continue;
        }

        // Insert attendance
        try {
            $insertStmt->execute([
                $institution_id,
                $branch_id,
                $student_id,
                $academic_id,
                $class_id,
                $section_id,
                $value,
                $date,
                $username,
                $username,
                time(),
                time()
            ]);

            file_put_contents($logSuccess, "[$processed/$total] Inserted: $admission_no on $date\n", FILE_APPEND);
            $successCount++;
        } catch (Exception $e) {
            file_put_contents($logError, "[$processed/$total] Insert Error: $admission_no on $date - " . $e->getMessage() . "\n", FILE_APPEND);
        }

        // Log progress every 10%
        if ($processed % max(1, floor($total / 10)) === 0) {
            $percentage = round(($processed / $total) * 100);
            file_put_contents($logProgress, "Progress: $percentage% ($processed/$total)\n", FILE_APPEND);
        }
    }

    // $conn_rjllearning_specific->commit();
    file_put_contents($logProgress, "Completed: Success=$successCount, Skipped=$skippedCount, Total=$total\n", FILE_APPEND);
    successreturn("Student attendance import completed. Success=$successCount, Skipped=$skippedCount");

} catch (Exception $e) {
    // $conn_rjllearning_specific->rollBack();
    file_put_contents($logError, "Transaction failed: " . $e->getMessage() . "\n", FILE_APPEND);
    errorreturn("Import failed: " . $e->getMessage());
}
