<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../../../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_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_resources . "includes/specific_db_config.php";
require_once $base_path_to_learning . "vendor/autoload.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 . '/user_management/check_username_availability.php';
require_once $base_path_to_learning . 'admin_api/modules/students/student_functions.php';
require_once $base_path_to_learning . 'user_management/faculty/functions.php';
require_once $base_path_to_learning . 'admin_api/modules/student_registration/functions/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/cache_student_academic_function.php';
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_add_alter_student_ledgers_finware.php';
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/cron_import/cron_import_students/import/function.php';
// use Aws\S3\S3Client;
// use Aws\S3\Exception\S3Exception;
// use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * Error handler: set status = -1 and save error_log
 */

function log_error_import_student(PDO $conn, int $rowId, string $msg): void {
    $stmt = $conn->prepare("
        UPDATE import_activity
           SET status = -1,
               error_log = ?,
               processed_end = NOW()
         WHERE id = ?
    ");
    $stmt->execute([$msg, $rowId]);
}

//  Fetch pending student files from import_file
$sql = "SELECT ia.*, ia.id AS import_id, ifl.file_name, ifl.file_path , ifl.uploaded_by 
          FROM import_activity ia 
          JOIN import_file ifl ON ia.import_file_id = ifl.id 
         WHERE ia.status IN (0,2)  
           AND ifl.file_type = 'students' 
         LIMIT 1";    

$stmt = $conn_rjllearning->prepare($sql);
$stmt->execute();
$file = $stmt->fetch(PDO::FETCH_ASSOC); 

if ($file) {
    $fileId         = $file['import_file_id'];
    $workspace_id   = $file['workspace_id'];
    $institution_id = $file['institution_id'];
    $import_id      = $file['import_id'];
// print_r($file);die();

    try {
        /** Duplicate check before processing */
        $chkDup = $conn_rjllearning->prepare("
            SELECT id FROM import_activity 
             WHERE import_file_id = ? AND status = 2 LIMIT 1
        ");
        $chkDup->execute([$fileId]);
        if ($chkDup->rowCount() > 0) {
            throw new Exception("This file has already been imported successfully before.");
        }
    
          // Check institution exists
        $chk = $conn_rjllearning->prepare("SELECT id FROM institutions WHERE id = ?");
        $chk->execute([$institution_id]);
        if ($chk->rowCount() == 0) {
            throw new Exception("Invalid institution_id $institution_id");
        }

        // // Update status to processing
        $stmtU = $conn_rjllearning->prepare("
            UPDATE import_activity SET status = 1, processed_start = NOW() WHERE id = ?
        ");
        $stmtU->execute([$import_id]);

        // import_activity created by -> users 
        $createdBy = $file['uploaded_by'];  

        $stmtUser = $conn_rjllearning->prepare("SELECT id AS userid, role, username FROM users WHERE username = ?");
        $stmtUser->execute([$createdBy]);
        $user = $stmtUser->fetch(PDO::FETCH_ASSOC);

        // if (!$user) {
        //     throw new Exception("Uploaded by user not found: $createdBy");
        // }

        $userid  = $user['userid'];
        $role    = $user['role']; 
        $username =$user['username'];

        // // Build postdata for import
        // $postdata['userid']   = $userid;
        // $postdata['role'] = $role;
        $postdata['workspace_id']  = $workspace_id;
        $postdata['institution_id']= $institution_id;
        $postdata['function_type'] = "import_students";
        $filePath= trim($file['file_path']);
        $fileName= $file['file_name'];

        // Run student import script
        require $base_path_to_learning_resources . "lib/common_modules/cron_import/cron_import_students/import/import_students.php";
        

        // Update status to success
        $stmtS = $conn_rjllearning->prepare("
            UPDATE import_activity SET status = 2, processed_end = NOW() WHERE id = ?
        ");
        $stmtS->execute([$import_id]);

    } catch (Exception $e) {
        log_error_import_student($conn_rjllearning, $import_id, $e->getMessage());
        $cron_error = $e->getMessage();
    }
}
?>