<?php

session_start();
include '../config/database.php';
include_once '../security/session_config.php';
include_once '../config/properties.php';
include_once "../resources/offering.php";

$user_id = intval($_SESSION['uid']);
$learning_path_id = intval($_GET['id']);

$offering = new Offering();
$offering->user_id = $user_id;
$offering->learning_path_id = $learning_path_id;

function generateCircleAndLine($name, $color, $isLast, $type, $link = null, $dependencyMessage = null, $wasDependency = false) {
    
    echo "<div class='circle-container'>";
    // Circle with an icon
    echo "<div class = 'circle' style=' background-color: {$color}; '>";
    if ($type === 'course') {
        echo "<i class='fa fa-fw fa-leanpub'></i>";
    } elseif ($type === 'assessment') {
        echo "<i class='fa fa-fw fa-pencil-square-o'></i>";
    }
    echo "</div>";

    // Vertical line (only if it's not the last element)
    if (!$isLast) {
        echo "<div class='vertical-line'></div>";
    }

    // Text content container (course name and dependency message)
    echo "<div class='text-container'>";

    echo "<span class='course-name-container'>";
    if ($wasDependency) {
        echo "<i class='fa fa-link'></i> "; // Icon before course name
    }
    echo "<span class='course-name'>";
    
    if($dependencyMessage == 'Y'){
        echo "<span class='hover-message'>" . htmlspecialchars(_('CRT3118')) . "</span>" ; 
    }
    // Course name (linked or plain)
    if ($link) {

        echo "<a href='{$link}' target='_blank' '>" . htmlentities($name) . "</a>";
    } else {
        echo "<span >" . htmlentities($name) . "</span>";
    }
    echo "</span>"; 
    echo "</div>";
    echo "</div>"; // Close text content container
    echo "</div>"; // Close main container
}

// Check if the user has completed the learning path
$stmt1 = $offering->learning_path_completed();
$num1 = $stmt1->rowCount();

if ($num1 > 0) {
    $certificate = "Yes";
    $complete = _("CRT5107");
    $stmt2 = $offering->learnings_course_display_complete();
    $num2 = $stmt2->rowCount();
    $courses = [];

    if ($num2 > 0) {
        while ($row2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
            $course_name = $row2['course_name'];

            $circle_color = '#28a745'; // Green color for completed
            // echo "<span style='display: inline-block; width: 20px; height: 20px;font-size: 25px; background-color: {$circle_color}; border-radius: 50%; margin-right: 10px;'></span>";
            // echo htmlentities($course_name)."</br>" ;
            // echo "</br>";
            $courses[] = ['name' => $course_name, 'color' => $circle_color, 'type' => 'course'];
        }
    }
    $stmt3 = $offering->learnings_assessment_display_complete();
    $num3 = $stmt3->rowCount();
    if ($num3 > 0) {
        while ($row3 = $stmt3->fetch(PDO::FETCH_ASSOC)) {
            $assessment_name = $row3['assessment_name'];

            $circle_color = '#28a745'; // Green color for completed
            // echo "<span style='display: inline-block; width: 20px; height: 20px;font-size: 25px; background-color: {$circle_color}; border-radius: 50%; margin-right: 10px;'></span>";
            // echo htmlentities($assessment_name) ."</br>" ;
            // echo "</br>";
            $courses[] = ['name' => $assessment_name, 'color' => $circle_color, 'type' => 'assessment'];
        }
    }
    // Render courses and assessments with conditional lines
    foreach ($courses as $index => $item) {
        $isLast = ($index === count($courses) - 1);
        generateCircleAndLine($item['name'], $item['color'], $isLast, $item['type']);
    }
} else {
    $certificate = "";
    $stmt2 = $offering->learnings_course_display();
    $num2 = $stmt2->rowCount();
    $courses = [];
    $completed_courses = [];
    $dependencyMessage = "";
    if ($num2 > 0) {
        while ($row2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
            $complete = "";
            $course_name = $row2['course_name'];
            $course_id = $row2['course_id'];
            $offering->course_id = $course_id;
            $dependecy = $row2['dependency'];

            $stmt5 = $offering->learnings_course_display_offer();
            $course_link = "";
            $num5 = $stmt5->rowCount();
            $offer_id = "";
            if ($num5 > 0) {
                $rows = $stmt5->fetchAll(PDO::FETCH_ASSOC); // Fetch all rows once

                foreach ($rows as $row5) { // Iterate through the array
                    if ($row5['course_id'] == $course_id) { // Ensure correct mapping
                        $offer_id = $row5['offering_id'];

                        $course_link = "courseview.php?offering=" . urlencode($offer_id);
                        break; // Stop once we find the right match
                    }
                }
            }

            $offering->offering_id = $offer_id;
            $stmt4 = $offering->check_learnings_status_course();
            $num4 = $stmt4->rowCount();
            if ($num4 > 0) {
                while ($row4 = $stmt4->fetch(PDO::FETCH_ASSOC)) {
                    if ($row4["complete"] != 0) {
                        $complete = _("CRT5107");
                        $completed_courses[$course_id] = true; // Mark as completed
                        $course_link = "";
                        $circle_color = '#5cb85c'; // Green for completed
                    } else if ($row4["incomplete"] != 0) {
                        $complete = _("CRT5106");
                        $circle_color = '#dc3545'; // Red for incomplete
                    } else {
                        $complete = "Not assigned";
                        $circle_color = '#6c757d'; // Gray for not assigned
                    }
                    // Handle dependency logic
                    if ($row2['dependency'] == "Y") {
                        $dependencyExists = false;
                        $course_names = [];
                        $dependencyMessage = "";
                        
                        $circle_color = '#FFCC33'; // Default: Yellow (Blocked)
                        $course_link = ""; // Default: Blocked
                        // Get learning paths for the offering
                        $learning_paths = $offering->get_learning_paths();
                        foreach ($learning_paths->fetchAll(PDO::FETCH_ASSOC) as $lp_row) {
                            $seq_no1 = $lp_row['seq_no'] - 1;

                            foreach ($offering->check_prev_learning_paths($lp_row['learning_path_id'], $seq_no1, $user_id)->fetchAll(PDO::FETCH_ASSOC) as $lp_row2) {
                                if ($lp_row2['count'] != 0 && $lp_row2['result'] == null && $lp_row2['status'] == 'Active') {
                                    // If the previous course is not completed, dependency still exists
                                    $course_names[] = $lp_row2['course_name'];
                                    $dependencyExists = true;
                                }
                            }
                        }

                        if ($dependencyExists) {
                            // Course is still blocked
                            $dependencyMessage = "Y";
                            $circle_color = '#FFCC33'; // Yellow (Blocked)
                            $course_link = ""; // No access
                        } else {
                            // Dependency is met, now check if the course itself is completed
                            if ($row4["complete"] != 0) {
                                // Course is completed
                                $dependencyMessage = null;
                                $circle_color = '#5cb85c';
                                $course_link = "";
                            } else {
                                // Dependency is cleared, course is accessible but incomplete
                                $dependencyMessage = null;
                                $course_link = "courseview.php?offering=" . rawurlencode($offering->offering_id);
                                $circle_color = '#dc3545'; // Red (Now Accessible but Incomplete)
                            }
                        }
                    }
                }
            } else {
                
            }
            $courses[] = ['name' => $course_name, 'color' => $circle_color, 'link' => $course_link, 'type' => 'course', 'dependencyMessage' => $dependencyMessage,'wasDependency' => ($dependecy == "Y") ];
        }
    }

    $stmt3 = $offering->learnings_assessment_display();
    $num3 = $stmt3->rowCount();
    if ($num3 > 0) {
        while ($row3 = $stmt3->fetch(PDO::FETCH_ASSOC)) {
            $complete = "";
            $assessment_name = $row3['assessment_name'];
            $assessment_id = $row3['assessment_id'];
            $offering->assessment_id = $assessment_id;
            $dependecy = $row3['dependency'];

            $stmt4 = $offering->check_learnings_status_assessment();
            $num4 = $stmt4->rowCount();

            if ($num4 > 0) {
                while ($row4 = $stmt4->fetch(PDO::FETCH_ASSOC)) {
                    if ($row4["complete"] != 0) {
                        $complete = _("CRT5107");

                        $circle_color = '#28a745'; // Green for completed
                    } else if ($row4["incomplete"] != 0) {
                        $complete = _("CRT5106");

                        $circle_color = '#dc3545'; // Red for incomplete
                    } else {
                        $complete = "Not assigned";

                        $circle_color = '#6c757d'; // Gray for not assigned
                    }
                }
            } else {
                
            }
            // echo "<span style='display: inline-block; width: 20px; height: 20px; font-size: 25px; background-color: {$circle_color}; border-radius: 50%; margin-right: 10px;'></span>";
            // echo htmlentities($assessment_name)."</br>"  ;
            // echo "</br>";
            $courses[] = ['name' => $assessment_name, 'color' => $circle_color, 'type' => 'assessment'];
        }
    }
    // Render courses and assessments with conditional lines
    foreach ($courses as $index => $item) {
        $isLast = ($index === count($courses) - 1);
        generateCircleAndLine($item['name'], $item['color'], $isLast, $item['type'], isset($item['link']) ? $item['link'] : null, $item['dependencyMessage'] ?? null, $item['wasDependency'] ?? false);
    }
}

if ($num1 == 0 && $num2 == 0 && $num3 == 0) {
    echo "No courses/Assessments Attched<br/>";
}
echo "<br/>";
?>
