<?php

// Set up error reporting
ini_set('display_errors', 1);

// Include necessary files
require_once '../../../resources/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';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

// Check if JSON is valid
// $postdata = json_decode(file_get_contents("php://input"), true);
// checkIfNoPhpContentsReceive();

 $postdata = $_POST;

// print_r($postdata);die();
$required_fields = ['class_id', 'section_id', 'name', 'api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}
//  $postdata = json_decode(file_get_contents('php://input'), true); // Assuming the POST data is sent as JSON

// $required_fields = ['institution_id', 'branch_id', 'class_id', 'section_id', 'name', 'api_signature', 'function_type', 'jwt_token'];
// foreach ($required_fields as $field) {
//     if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
//         errorreturn("Missing required field: $field");
//     }
// }


validateApiSignature($postdata['api_signature']);

// Authenticate user and get user details
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

// Validate user access to specific database
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
// Include necessary function files
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

// Validate basic parameters
// $function_type = trim($postdata['function_type']);

$class_id = trim($postdata['class_id']);
// $subject_id = isset($postdata['subject_id']) ? trim($postdata['subject_id']) : null; // cannot be null ~~~~~~
$subject_id = trim($postdata['subject_id']);
$branch_id = trim($postdata['branch_id']);
$section_id = trim($postdata['section_id']);
$name = ucwords(trim($postdata['name']));
$display_question_by = ucwords(trim($postdata['display_question_by']));
$date_created = date('Y-m-d');
$time_created = time();
// $status = trim($postdata['status']) ;
$status = 1;
$max_points = isset($postdata['max_points']) ? trim($postdata['max_points']) : 0;
$description = trim($postdata['description']);
$timer = ($postdata['timer']);

if (isset($postdata['publish_date']) && isset($postdata['last_date']) && strtotime($postdata['publish_date']) <= strtotime($postdata['last_date'])) {
    $publish_date = date('Y-m-d', strtotime($postdata['publish_date']));
} else {
    $publish_date = date('Y-m-d');
}
if (isset($postdata['last_date']) && isset($postdata['publish_date']) && strtotime($postdata['last_date']) >= strtotime($postdata['publish_date'])) {
    $last_date = date('Y-m-d', strtotime($postdata['last_date']));
} else {
    $last_date = date('Y-m-d');
}
//$timer = time();

$publish_time = isset($postdata['publish_time']) ? ($postdata['publish_time']) : false;
$last_submission_time = isset($postdata['last_submission_time']) ? ($postdata['last_submission_time']) : false;

// Check if the publish_time and last_submission_time are valid timestamps
if ($publish_time === false || $last_submission_time === false) {
    errorreturn("Invalid date format for publish time or last submission time.");
}

// Ensure publish_time is before last_submission_time
if ($publish_time >= $last_submission_time) {
    errorreturn("Invalid Date Range: publis time must be before last submission time.");
}

// $last_submission_time =  isset($postdata['last_submission_time']) && isset($postdata['publish_time']) && strtotime($postdata['last_submission_time']) > strtotime($postdata['publish_time']) ? strtotime($postdata['last_submission_time']) : time();

if (isset($postdata['can_submit_after_last_date'])) {
    $can_submit_after_last_date = intval($postdata['can_submit_after_last_date']);
} else {
    $can_submit_after_last_date = 0;
}

$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

if ($status !== null && !in_array($status, [0, 1, 2])) {
    errorreturn('Invalid status value.');
}

if (!CheckStartDate($publish_date)) {
    //eg House Name, Street Name
    errorreturn('Invalid Date Format');
}

if (!CheckStartDate($last_date)) {
    //eg House Name, Street Name
    errorreturn('Invalid Date Format');
}
// echo"$publish_date,$last_date";
// die();

if ($publish_date >= $last_date) {
    errorreturn('Invalid Date Range');
} 

if (!CheckValidateTime($publish_time)) {
    errorreturn('Invalid End time');
}

if (!CheckValidateTime($last_submission_time)) {
    errorreturn('Invalid End time');
}

if ($publish_time >= $last_submission_time) {
    errorreturn('Invalid time Range');
}

$check_branch_class = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, $subject_id, $institution_id);
if ($check_branch_class == false) {
    errorreturn("Access denied");
}



//  print_r($finalised_question_array);die();
if ($postdata['function_type'] == 'create_test') {

    $max_points = 0;


    // Check if test with the same name already exists
   $testExistenceQuery = "SELECT id FROM test WHERE institution_id = ?   AND branch_id = ?   AND class_id = ?   AND (section_id = ? OR section_id = ?)   AND name = ?  AND ((publish_time = ? AND last_date = ?) OR (publish_time = ? AND last_submission_time = ?))";
   $testExistenceStmt = $conn_rjllearning_specific->prepare($testExistenceQuery);
   $testExistenceStmt->execute([$institution_id, $branch_id, $class_id, $section_id, 'all', $name, $publish_time, $last_date, $publish_time, $last_submission_time]);
   if (count($testExistenceStmt->fetchAll()) >= 1) {
       errorreturn("Test with the same name already exists or publish time and date conflict.");
   }


    try {
        // Start transaction
        $conn_rjllearning_specific->beginTransaction();

        // Insert into test table
        $inserttestQuery = "INSERT INTO test (institution_id, branch_id, class_id, section_id, subject_id, name, description, max_points, publish_date, last_date, publish_time, last_submission_time,timer,display_question_by, added_by, last_modified_by, date_created, time_created, status) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $inserttesttmt = $conn_rjllearning_specific->prepare($inserttestQuery);
        $inserttesttmt->execute([$institution_id, $branch_id, $class_id, $section_id, $subject_id, $name, $description, $max_points, $publish_date, $last_date, $publish_time, $last_submission_time,$timer,$display_question_by, $username, $username, $date_created, $time_created, $status]);

        // Get the last inserted test ID
        $test_id = $conn_rjllearning_specific->lastInsertId();


       
        // Commit transaction
        $conn_rjllearning_specific->commit();

        successreturn(['id' => $test_id, 'successmsg' => "Successfully added test."]);
    } catch (Exception $e) {
        // Rollback transaction in case of error
        $conn_rjllearning_specific->rollBack();
        echo "Failed to insert test and questions: " . $e->getMessage();
    }
} else if ($postdata['function_type'] == 'alter_test') {
    // Check if test ID is provided
    if (!isset($postdata['test_id'])) {
        errorreturn("test ID not provided.");
    }

    $test_id = $postdata['test_id'];

    // Check if test exists
    $testExistenceQuery = "SELECT id FROM test WHERE id = ? AND institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ? ";
    $testExistenceStmt = $conn_rjllearning_specific->prepare($testExistenceQuery);
    $testExistenceStmt->execute([$test_id,$institution_id, $branch_id, $class_id, $section_id]);
    $result = $testExistenceStmt->fetchAll();
    if (count($result) < 1) {
        errorreturn("Test not found.");
    }
    
      // Check if test exists
    // $testExistenceQuery = "SELECT id FROM test WHERE id != ? AND institution_id = ? AND branch_id = ? AND (class_id = ? OR section_id = ? OR publish_date = ? AND last_date = ? OR publish_time = ? OR last_submission_time = ?)";
    // $testExistenceStmt = $conn_rjllearning_specific->prepare($testExistenceQuery);
    // $testExistenceStmt->execute([$test_id,$institution_id, $branch_id, $class_id, $section_id,$publish_date,$last_date,$publish_time,$last_submission_time]);
    // $result = $testExistenceStmt->fetchAll();
    // if (count($result) > 1) {
    //     errorreturn("Test already exists.");
    // }


    // Update test in the database
    $updatetestQuery = "UPDATE test SET class_id = ?, section_id = ?, subject_id  = ?, name = ?, description = ?, max_points = ?, publish_date = ?, last_date = ?,  publish_time = ?, last_submission_time = ?, last_modified_by = ? WHERE id = ? AND institution_id = ?";
    $updatetesttmt = $conn_rjllearning_specific->prepare($updatetestQuery);

    // Bind parameters and execute update
    $updatetesttmt->execute([
        $class_id, 
        $section_id, 
        $subject_id,
        $name,
        $description,
        $max_points,
        $publish_date,
        $last_date,
        $publish_time,
        $last_submission_time,
        $username,
        $test_id,
        $institution_id
    ]);

  
    // Check if any rows were affected
     successreturn("test updated successfully.");
    // if ($updatetesttmt->rowCount() > 0) {
    //     successreturn("test updated successfully.");
    // } else {
    //     errorreturn("No changes made to the test.");
    // }
}
