<?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';

//dynemic db
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';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !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  !checkIfIssetAndNotEmpty($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;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'admin'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $postdata['institution_id']);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

// Function to create a new activity
function createActivityPlanner($conn, $data, $created_by) {
    // Encode schedule details as JSON
    $scheduleDetailsJson = json_encode($data['schedule_details']);
    $createdIds = [];

    // Extract IDs or use "all" as literal
    $branchIds  = ($data['branch_id'] === 'all') ? ['all'] : (array) $data['branch_id'];
    $classIds   = ($data['class_id'] === 'all') ? ['all'] : (array) $data['class_id'];
    $sectionIds = ($data['section_id'] === 'all') ? ['all'] : (array) $data['section_id'];
    $facultyIds = ($data['faculty_id'] === 'all') ? ['all'] : (array) $data['faculty_id'];

    // If any field is 'all', insert only one row with literal 'all'
    if (
        $branchIds === ['all'] ||
        $classIds === ['all'] ||
        $sectionIds === ['all'] ||
        $facultyIds === ['all']
    ) {
        $stmt = $conn->prepare("INSERT INTO activity_planner (
                                    institution_id, activity_name, activity_type, 
                                    branch_id, class_id, section_id, faculty_id, 
                                    description, from_date, to_date, schedule_details, 
                                    status, created_by, date_created, last_modified_by, last_modified_at
                                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $data['institution_id'],
            $data['activity_name'],
            $data['activity_type'],
            $branchIds[0],
            $classIds[0],
            $sectionIds[0],
            $facultyIds[0],
            $data['description'],
            $data['from_date'],
            $data['to_date'],
            $scheduleDetailsJson,
            1,
            $created_by,
            date('Y-m-d H:i:s'),
            $created_by,
            date('Y-m-d H:i:s')
        ]);
        $createdIds[] = $conn->lastInsertId();
    } else {
        // All values are specific — insert all combinations
       foreach ($branchIds as $branchId) {
    // Check if branch exists
    // if ($branchId !== 'all') {
    //     $stmt = $conn->prepare("SELECT COUNT(*) FROM branches WHERE branch_id = ?");
    //     $stmt->execute([$branchId]);
    //     if ($stmt->fetchColumn() == 0) continue; // Skip invalid branch
    // }

    foreach ($facultyIds as $facultyId) {
        // Check if faculty exists and (optionally) belongs to the branch
        // if ($facultyId !== 'all') {
        //     $stmt = $conn->prepare("SELECT COUNT(*) FROM faculty WHERE faculty_id = ?" . ($branchId !== 'all' ? " AND branch_id = ?" : ""));
        //     $stmt->execute($branchId !== 'all' ? [$facultyId, $branchId] : [$facultyId]);
        //     if ($stmt->fetchColumn() == 0) continue; // Skip if invalid or mismatched with branch
        // }

        foreach ($classIds as $classId) {
            // Check if class exists
            // if ($classId !== 'all') {
            //     $stmt = $conn->prepare("SELECT COUNT(*) FROM classes WHERE class_id = ?");
            //     $stmt->execute([$classId]);
            //     if ($stmt->fetchColumn() == 0) continue;
            // }

            foreach ($sectionIds as $sectionId) {
                // Check if section exists
                // if ($sectionId !== 'all') {
                //     $stmt = $conn->prepare("SELECT COUNT(*) FROM sections WHERE section_id = ?");
                //     $stmt->execute([$sectionId]);
                //     if ($stmt->fetchColumn() == 0) continue;
                // }

                // All checks passed – insert activity
                $stmt = $conn->prepare("INSERT INTO activity_planner (
                                            institution_id, activity_name, activity_type, 
                                            branch_id, class_id, section_id, faculty_id, 
                                            description, from_date, to_date, schedule_details, 
                                            status, created_by, date_created, last_modified_by, last_modified_at
                                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $data['institution_id'],
                    $data['activity_name'],
                    $data['activity_type'],
                    $branchId,
                    $classId,
                    $sectionId,
                    $facultyId,
                    $data['description'],
                    $data['from_date'],
                    $data['to_date'],
                    $scheduleDetailsJson,
                    1,
                    $created_by,
                    date('Y-m-d'),
                    $created_by,
                    date('Y-m-d')
                ]);
                $createdIds[] = $conn->lastInsertId();
            }
        }
    }
}

    }

    // Final return
    return [
        'message' => 'Activity created successfully for ' . count($createdIds) . ' combination(s).',
        'activity_ids' => $createdIds
    ];
}


// Function to update an existing activity
function updateActivityPlanner($conn, $data, $modified_by) {
    $sql = "UPDATE activity_planner SET activity_name = ?, activity_type = ?, branch_id = ?, class_id = ?, section_id = ?, faculty_id = ?, description = ?, from_date = ?, to_date = ?, schedule_details = ?, status = ?, last_modified_by = ?, last_modified_at = NOW()
            WHERE id = ? AND institution_id = ?";

    $stmt = $conn->prepare($sql);
    $stmt->execute([
        $data['activity_name'], 
        $data['activity_type'], 
        $data['branch_id'], 
        $data['class_id'], 
        $data['section_id'], 
        $data['faculty_id'], 
        $data['description'], 
        $data['from_date'], 
        $data['to_date'], 
        json_encode($data['schedule_details']), 
        1, 
        $modified_by, 
        $data['activty_planner_id'], 
        $data['institution_id']
    ]);

    return ['message' => 'Activity Updated Successfully', 'activity_id' => $data['activty_planner_id']];
}

// Handle API function types
if ($postdata['function_type'] == "create_activity") {
    $requiredFields = ['activity_name', 'activity_type', 'from_date'];

    foreach ($requiredFields as $field) {
        if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
            errorreturn("Missing or empty required field: $field");
        }
    }


    $response = createActivityPlanner($conn_rjllearning_specific, $postdata, $username);
    successreturn($response);

} elseif ($postdata['function_type'] == "update_activity") {
    if (
        !isset($postdata['activty_planner_id']) or !checkIfIssetAndNotEmpty($postdata['activty_planner_id']) or
        !isset($postdata['activity_name']) or !checkIfIssetAndNotEmpty($postdata['activity_name']) or
        !isset($postdata['activity_type']) or !checkIfIssetAndNotEmpty($postdata['activity_type']) or
        !isset($postdata['from_date']) or !checkIfIssetAndNotEmpty($postdata['from_date'])
    ) {
        errorreturn("Missing required fields.");
    }

    $response = updateActivityPlanner($conn_rjllearning_specific, $postdata, $username);
    successreturn($response);

} else {
    errorreturn("Invalid function_type.");
}
