<?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 . '/user_management/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.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_resources . "lib/function.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';

/**
 * Error handler
 */
function log_error_import_transport(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]);
}


// 1. Fetch pending OR already processed transport files
$sql = "SELECT ia.*, ia.id AS import_id, ifl.file_name, ifl.file_path, ifl.file_type 
          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 IN ('buses','bus_stops','routes') 
         LIMIT 1";    

$stmt = $conn_rjllearning->prepare($sql);
$stmt->execute();
$file = $stmt->fetch(PDO::FETCH_ASSOC); 
// print_r($file);die();
if ($file) {
    $fileId        = $file['import_file_id'];
    $workspaceId   = $file['workspace_id'];
    $institutionId = $file['institution_id'];
    $import_id     = $file['import_id'];

    try {
        // 2. Duplicate check (if already successfully imported, stop)
        $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.");
        }

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

        // 4. Validate institution
        $chk = $conn_rjllearning->prepare("SELECT id FROM institutions WHERE id = ?");
        $chk->execute([$institutionId]);
        if ($chk->rowCount() == 0) {
            throw new Exception("Invalid institution_id $institutionId");
        }

        // 5. JWT token
        $stmtJ = $conn_rjllearning->prepare("SELECT jwttoken FROM user_log WHERE workspace_id = ? LIMIT 1");
        $stmtJ->execute([$workspaceId]);
        $jwt = $stmtJ->fetch(PDO::FETCH_ASSOC);
        if (!$jwt) {
            throw new Exception("JWT not found for workspace $workspaceId");
        }
        $jwt_payload = authenticate_jwt($jwt['jwttoken']);
        $userid      = $jwt_payload->data->id;
        $role        = $jwt_payload->data->role;
        $workspace_id= $jwt_payload->data->workspace_id;
        $username    = $jwt_payload->data->username;

        $filePath = trim($file['file_path']);

        // 6. Common POST variables
        $postdata['jwt_token']      = $jwt["jwttoken"];
        $postdata['api_signature']  = "WR5yGWg6mG";
        $postdata['userid']         = $userid;
        $postdata['role']           = $role;
        $postdata['workspace_id']   = $workspace_id;
        $postdata['institution_id'] = $institutionId;
        $filePath=trim($file['file_path']);
        $fileName = $file['file_name'];

        // 7. Switch on file_type and include proper import script
        switch ($file['file_type']) {
            case 'buses':
                $_POST['function_type'] = "import_bus";
                require $base_path_to_learning_resources . "/lib/common_modules/cron_import/cron_import_transaport/import/import_buses_data.php";
                break;

            case 'bus_stops':
                $_POST['function_type'] = "import_bus_stops";
                require $base_path_to_learning_resources . "lib/common_modules/cron_import/cron_import_transaport/import/import_bus_stops.php";
                break;

            case 'routes':
                $_POST['function_type'] = "import_bus_routes";
                require $base_path_to_learning_resources . "lib/common_modules/cron_import/cron_import_transaport/import/import_bus_routes.php";
                break;

            default:
                throw new Exception("Unknown transport file_type: " . $file['file_type']);
        }
        
        // 8. Success update
        $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_transport($conn_rjllearning, $import_id, $e->getMessage());
        $cron_error = $e->getMessage();
    }
}
?>
