<?php
ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
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 . 'functions/common_functions.php';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

//aws image store
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";

require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

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

$postdata =$_POST; 

// $postdata = json_decode(file_get_contents("php://input"), true);
// print_r($postdata);
// checkIfNoPhpContentsReceive();

/*
 * Basic required fields (keeps your original required checks)
 */
if (
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) or
    !isset($postdata['jwt_token']) or  !isset($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}
validateApiSignature($postdata['api_signature']);

$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;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;
$class_id = $jwt_validate->data->class;
$section_id = $jwt_validate->data->section;

require_once $base_path_to_learning . 'functions/get_branch_functions.php';
$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["student"], null, null, $userid);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
validateStudentClassSection($conn_rjllearning_specific, $userid, $institution_id, $branch_id, $class_id, $section_id);

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

/*
 * Optional but important checks for task_id and submission payload.
 * (If your frontend always passes these, they just guard against empty values)
 */
$task_id = isset($postdata['task_id']) ? trim($postdata['task_id']) : '';
$submission_data = isset($postdata['submission']) ? $postdata['submission'] : null;

if ($postdata['function_type'] === "submit_speech_task") {

    try {
        if (empty($task_id)) {
            errorreturn("Task id is required.");
        }
        // Check if submission comes from form-data (file upload)
        if (isset($_FILES['submission']) && $_FILES['submission']['error'] === 0) {
            $submission_data = $_FILES['submission'];  // file array
        } elseif (isset($postdata['submission'])) {
            $submission_data = $postdata['submission']; // JSON body
        } else {
            errorreturn("Submission data is required.");
        }

        // 1. First check if the task exists and get its details (single row)
        $sql_task = "SELECT * FROM speech_tasks WHERE id = ? AND status = 1";
        $stmt_task = $conn_rjllearning->prepare($sql_task);
        $stmt_task->execute([$task_id]);
        $task = $stmt_task->fetch(PDO::FETCH_ASSOC);

        if (!$task) {
            errorreturn("Speech task not found or inactive.");
        }

        // 2. Get student details to check eligibility (age)
        $sql_student = "SELECT TIMESTAMPDIFF(YEAR, s.dob, CURDATE()) as age
                FROM students s
                WHERE s.user_id = ? AND s.institution_id = ? AND s.branch_id = ?";
        $stmt_student = $conn_rjllearning_specific->prepare($sql_student);
        $stmt_student->execute([$userid, $institution_id, $branch_id]);
        $student = $stmt_student->fetch(PDO::FETCH_ASSOC);


        if (!$student) {
            errorreturn("Student not found.");
        }

        $is_eligible = false;
        
        // Determine if task is age-based or class/section-based
        $ids_all_null = is_null($task['workspace_id']) && is_null($task['institution_id']) && is_null($task['branch_id']) && is_null($task['academic_id']);
        
        if ($ids_all_null) {
            // Age-based task: check min_age and max_age
            if ($task['min_age'] !== null && $task['max_age'] !== null && $task['min_age'] !== '' && $task['max_age'] !== '') {
                $min_age = intval($task['min_age']);
                $max_age = intval($task['max_age']);
                $student_age = intval($student['age']);
                if ($student_age >= $min_age && $student_age <= $max_age) {
                    $is_eligible = true;
                }
            }
        } else {
            // Class/section-based task: check 4 IDs + class/section
            if (
                intval($task['workspace_id']) === intval($workspace_id) &&
                intval($task['institution_id']) === intval($institution_id) &&
                intval($task['branch_id']) === intval($branch_id) &&
                intval($task['academic_id']) === intval($academic_id)
            ) {
                if ((string)$class_id === (string)$task['class_id'] && (string)$section_id === (string)$task['section_id']) {
                    $is_eligible = true;
                }
            }
        }
        
        // if (!$is_eligible) {
        //     errorreturn("You are not eligible for this speech task.");
        // }

        
        // 4. Check for previous submissions for same task_id & student_id
        $sql_previous = "SELECT another_attempt_requested FROM speech_tasks_submission WHERE task_id = ? AND student_id = ? ORDER BY submitted_at DESC LIMIT 1";
        $stmt_previous = $conn_rjllearning->prepare($sql_previous);
        $stmt_previous->execute([$task_id, $userid]);
        $previous_submission = $stmt_previous->fetch(PDO::FETCH_ASSOC);

        if ($previous_submission) {
            // DB default may be NULL; treat NULL as 0 (i.e. not allowed)
            $another_attempt = isset($previous_submission['another_attempt_requested']) ? intval($previous_submission['another_attempt_requested']) : 0;
            if ($another_attempt !== 1) {
                errorreturn("Another attempt is not allowed for this task.");
            }
        }

         // 6. Handle file upload + Decide submission/thumbnail paths based on allowed_type
        $allowed_type = isset($task['allowed_type']) ? strtolower(trim($task['allowed_type'])) : '';
        $submission_url = null;
        $thumbnail_url  = null;

        // === Upload Handling with S3 Integration ===
       if (!empty($_FILES['submission']) && $_FILES['submission']['error'] === UPLOAD_ERR_OK) {

            $currentYear  = date('Y');
            $currentMonth = date('m');

            $directoryPathMain = "user_uploads/{$workspace_id}/{$institution_id}/speech_tasks/{$currentYear}/{$currentMonth}/";
            $baseUploadPath    = "/home/rejoicebilldesk/public_html/rjllearning_development/" . $directoryPathMain;

            $file_name_new = "speech_task_" . time() . "_" . rand(1000, 9999) . "." .
                strtolower(pathinfo($_FILES['submission']['name'], PATHINFO_EXTENSION));

            $submission_path = $directoryPathMain . $file_name_new;
            $localFilePath   = $baseUploadPath . $file_name_new;

            if (!is_dir($baseUploadPath)) {
                mkdir($baseUploadPath, 0777, true);
            }

            if (!move_uploaded_file($_FILES['submission']['tmp_name'], $localFilePath)) {
                errorreturn("Failed to upload submission file.");
            }

            $_FILES['submission']['tmp_name'] = $localFilePath;

            $s3_upload_result = awsS3UserUploadInsert(
                $s3_learning_bucket,
                $learning_bucketName,
                $_FILES['submission'],
                $submission_path
            );

            $submission_url = $submission_path;

        } else {
            errorreturn("No file provided for submission.");
        }

        // Decide storage by allowed_type
        if ($allowed_type === 'audio') {
            if (empty($submission_url)) {
                errorreturn("Submission file (audio) not provided.");
            }
            $thumbnail_url = null;
        } elseif ($allowed_type === 'video') {
            if (empty($submission_url)) {
                errorreturn("Submission file (video) not provided.");
            }
            $thumbnail_url = null;
        } else {
            errorreturn("Invalid task allowed_type. Allowed values: 'audio' or 'video'.");
        }
        
        // 7. Insert the submission row into speech_tasks_submission
     $stmt_insert = $conn_rjllearning->prepare("
            INSERT INTO speech_tasks_submission (
                workspace_id, institution_id, branch_id, academic_id, task_id, student_id, submission, thumbnail,
                submitted_on, submitted_at, remarks, rating, phoneme, stress, intonation
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURDATE(), NOW(), NULL, NULL, NULL, NULL, NULL)
        ");

        $stmt_insert->execute([
            $workspace_id,
            $institution_id,
            $branch_id,
            $academic_id,
            $task_id,
            $userid,
            $submission_url,
            $thumbnail_url
        ]);

        $submission_id = $conn_rjllearning->lastInsertId();

        successreturn([
            "submission_id" => $submission_id,
            "successmsg" => "Speech task submitted successfully."
        ]);
    } catch (Exception $e) {
        errorreturn("Database Error: " . $e->getMessage());
    }
} else {
    errorreturn("Invalid function type.");
}
