<?php

// start session
 session_start();
// $_SESSION['LAST_ACTIVITY'] = time(); 
include_once "../config/database.php";
include_once '../security/session_config.php';
include_once '../security/csrf.php';
include_once "../resources/offering.php";
include_once '../config/properties.php';
$csrf_token = $_POST['csrf_token'];
validate_csrf_request($csrf_token);

$offering = new Offering();
// if (!isset($_SESSION['uid'])) {
//     echo "<script>window.location='../index.php';</script>";
// } else {
    $oid = $_POST['oid'];
    //    $uid = $_GET['uid'];
    $mode = $_POST['mode'];

    $offering->user_id = $_SESSION['uid'];
    $offering->offering_id = $oid;
    $offering->datetime = $date_time;

    if ($mode == "completed") {
        $cid = $_POST['cid'];
        $offering->contentdtl_id = $cid;
        if ($offering->track_content_complete()) {
            //            $current_track_count = $offering->offering_current_track_count($oid, $uid);
//            $total_content_count = $offering->offering_total_content_count($oid);
//            $val = intVal(($current_track_count * 100) / $total_content_count);
            if ($comp = $offering->cal_update_completion()) {
                echo $comp;
                if ($comp == "100") {
                    $offering->date = $date;
                    $stmt_criteria = $offering->check_course_criteria_ref();
                    if ($stmt_criteria->rowCount() > 0) {
                        $row = $stmt_criteria->fetch(PDO::FETCH_ASSOC);
                        extract($row);
                        $offering->attended_date = $date_time;
                        $offering->result = "complete";
                        $offering->score = 0;
                        $completion_points = NULL;

                        if ($offering->isCertificatepoints()) {
                            //removed
//                            $stmt_point = $offering->completion_pt_certificate_null();
//                            if ($stmt_point->rowCount() > 0) {
//                                $row_point = $stmt_point->fetch(PDO::FETCH_NUM);
//                                extract($row_point);
//                                $completion_points = $row_point['completion_points'];
//                            }
                            $stmt12 = $offering->completion_pt_certificate();
                            if ($stmt12 == NULL) {
                                $completion_points = $offering->completion_pt_assignment();
                            } else {
                                $completion_points = $stmt12;
                            }
                        } else {
                            $stmt14 = $offering->completion_pt_assignment();
                            $completion_points = $stmt14;
                        }

                        $offering->completion_points = $completion_points;
                        $offering->last_updated_ts = $date_time;
                        $val = $offering->update_result();
                        if ($val) {
                            $points = $offering->Sum_completionPoints();
                            if ($points != NULL) {
                                $update_pt = $offering->update_userpoint($points);
                                if ($update_pt) {

                                }
                            }
                            //                            if($offering->update_timediff()){}
                        }
                    }
                }
            } else {
                echo 'error';
                return -1;
            }
        }
    } else if ($mode == "incompleted") {
        $cid = $_POST['cid'];
        $offering->contentdtl_id = $cid;
        if ($offering->track_content_incomplete()) {
            if ($comp = $offering->cal_update_completion()) {
                echo $comp;
                if ($comp != "100") {
                    $offering->date = $date;
                    $stmt_criteria = $offering->check_course_criteria_ref();
                    if ($stmt_criteria->rowCount() > 0) {
                        $offering->attended_date = $date_time;
                        $offering->result = null;
                        $offering->score = 0;
                        $offering->last_updated_ts = $date_time;
                        $val = $offering->update_result();
                        if ($val) {

                        }
                    }
                }
            }
        } else {
            echo 'error';
            return -1;
        }
    } else if ($mode == "view") {
        $cid = $_POST['cid'];
        $offering->contentdtl_id = $cid;
        if ($offering->track_content_view()) {

        } else {
            echo 'error';
            return -1;
        }
    } else if ($mode == "time") {
        $cid = $_POST['cid'];
        $time_diff = '';

        if ($_POST['time_diff'] == '' || $_POST['time_diff'] == null) {
            $time_diff = NULL;
        } else {
            if ($_POST['type'] == "video") {
                $seconds = intval($_POST['time_diff']);
                $time_diff = gmdate("H:i:s", $seconds);
            } else {
                $time_diff = NULL;
            }
        }

        $offering->contentdtl_id = $cid;
        $offering->time_diff = $time_diff;
        $offering->total_time = $_POST['time'];
        if ($offering->time_track()) {

        } else {
            echo 'error';
            return -1;
        }
    } else if ($mode == "download") {

        $cid = $_POST['cid'];
        $offering->contentdtl_id = $cid;
        $f = trim($_POST['path']);

        if ($offering->track_content_download()) {
            /* $file = ADMIN_HTTP_PATH . $properties['jdbc.content_folder'] . '/' . $f;
              header("Content-Description: File Transfer");
              header("Content-Type: application/octet-stream");
              header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
              flush();
              readfile($file); */
            $file = ADMIN_HTTP_PATH . $properties['jdbc.content_folder'] . '/' . $f;
            $file = str_replace(' ', '%20', $file); // Ensure spaces are URL encoded
            $ch = curl_init($file);

            // Set cURL options
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the file content as a string
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow any "Location:" header
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);          // Set the timeout for the request
            curl_setopt($ch, CURLOPT_FAILONERROR, true);    // Fail on HTTP error
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Force HTTP/1.1
            // Execute the cURL session
            $fileContent = curl_exec($ch);

            // Check if the download was successful
            if ($fileContent === FALSE) {
                die('Failed to download file: ' . curl_error($ch));
            }

            // Get the content type and size
            $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
            $contentLength = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);

            // Close the cURL session
            curl_close($ch);

            // Set headers to serve the file to the client
            header("Content-Description: File Transfer");
            header("Content-Type: " . $contentType);
            header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
            header("Content-Length: " . $contentLength);
            header("Expires: 0");
            header("Cache-Control: must-revalidate");
            header("Pragma: public");

            // Output the file content
            echo $fileContent;
            exit;
        } else {
            echo 'error';
            return -1;
        }
    } else if ($mode == "video_viewed") {
        $cid = $_POST['cid'];
        $time = $_POST['time'];
        $offering->total_time = $time;
        $offering->contentdtl_id = $cid;
        $offering->track_content_video_complete();
    }
?>