<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('Asia/Kolkata');

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 . '/user_management/check_username_availability.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 . 'admin_api/modules/staff/staff_details/staff_functions.php';
require_once $base_path_to_learning . 'user_management/user_versioning.php';

/**
 * Error handler: set status = -1 and save error_log
 */
function log_error_import_faculty(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 faculty 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 = 'faculty' LIMIT 1";    
    $stmt = $conn_rjllearning->prepare($sql);
    $stmt->execute();
    $file = $stmt->fetch(PDO::FETCH_ASSOC); 
    // print_r($file);die();
    
    if ($file) {   // check if a pending row exists
    $fileId       = $file['import_file_id'];
    $workspace_id  = $file['workspace_id'];
    $institution_id= $file['institution_id'];
    $import_id= $file['import_id'];
    
        // Begin transaction
        // $conn_rjllearning->beginTransaction();
        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.");
            }
                
            //  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);
            //  print_r($user);die();
            $userid = $user['userid'];   //plain variable
            $role   = $user['role']; 
            $postdata['userid'] = $user['userid'];
            $postdata['role'] = $user['role'];
            $postdata['workspace_id'] =$workspace_id;
            $postdata['institution_id'] = $institution_id;
            $postdata['function_type'] = "import_faculty";
            $filePath=trim($file['file_path']);
            $fileName = $file['file_name'];

            require $base_path_to_learning_resources . "lib/common_modules/cron_import/cron_import_faculty/import/import_excel_faculty.php";
        
            //  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");
            }
            
             
            // Commit transaction if import successful
            // $conn_rjllearning->commit();

        //  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_faculty($conn_rjllearning, $import_id, $e->getMessage());
        $cron_error = $e->getMessage();
    }
    }
?>
