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

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';
require_once $base_path_to_learning . 'admin_api/modules/students/student_functions.php';
require_once $base_path_to_learning_resources . 'lib/cron_jobs/function/function.php';
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 . 'admin_api/modules/homework/homework_template_function.php';

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

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

$required_fields = [ 'product_name', 'api_signature', 'function_type', 'jwt_token', 'category_id'];

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

validateApiSignature($postdata['api_signature']);
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

if (!$jwt_validate) {
    errorreturn("Invalid JWT Token.");
}

$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;


$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['principal'], null);
if (!$specific_db_name) {
    errorreturn("Access denied.");
}
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

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);

// $institution_id = trim($postdata['institution_id']);
$product_name = trim(ucwords($postdata['product_name']));
$category_id = trim($postdata['category_id']);
$can_repeat = trim($postdata['can_repeat']);
$sale_distribute = trim($postdata['sale_distribute']);
$send_otp = trim($postdata['send_otp']);
$item_code = trim($postdata['item_code']);

if (!in_array($can_repeat, ['0', '1'], true)) {
    errorreturn("Invalid can_repeat value. It must be 0 or 1.");
}
if (!in_array($send_otp, ['0', '1'], true)) {
    errorreturn("Invalid send_otp value. It must be 0 or 1.");
}
if (!in_array($sale_distribute, ['0', '1'], true)) {
    errorreturn("Invalid sale_distribute value. It must be 0 or 1.");
}

if ($sale_distribute == 1) {
    $price = trim($postdata['price']);
} else {
    $price = null;
}

$sql = "SELECT id FROM items_category WHERE id = ? AND institution_id = ?";
$stmt = $conn_rjllearning_specific->prepare($sql);
$stmt->execute([$category_id, $institution_id]);
if (!$stmt->fetch()) {
    errorreturn("Enter a valid category.");
}

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

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

    try {

        $sql = "SELECT product_name FROM product_items WHERE institution_id = ? AND product_name = ?";
        // $sql = "SELECT product_name FROM product_items WHERE institution_id = ? AND product_name = ? AND category_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$institution_id, $product_name]);
        if ($stmt->fetch()) {
            errorreturn("A product with the same name already exists.");
        }

        $sql = "INSERT INTO product_items (institution_id, product_name, category_id, can_repeat, item_code, send_otp, sale_distribute, price, added_by, date_created, time_created, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([
            $institution_id,
            $product_name,
            $category_id,
            $can_repeat,
            $item_code,
            $send_otp,
            $sale_distribute,
            $price,
            $username,
            date('Y-m-d'),
            time(),
            1
        ]);

        $id = $conn_rjllearning_specific->lastInsertId();
        successreturn(["id" => $id, "successmsg" => "Item added successfully."]);
    } catch (Exception $e) {
        errorreturn("Database Error: " . $e->getMessage());
    }
} else if ($postdata['function_type'] == "alter_items") {

    if (!isset($postdata['product_id']) or !checkIfIssetAndNotEmpty($postdata['product_id'])) {
        errorreturn('Error in updating the item.');
    } else {
        $product_id = trim($postdata['product_id']);
    }

    try {
        // Check if the product exists
        $sql_check = "SELECT id FROM product_items WHERE institution_id = ? AND id = ?";
        $stmt_check = $conn_rjllearning_specific->prepare($sql_check);
        $stmt_check->execute([$institution_id, $product_id]);

        if ($stmt_check->rowCount() == 0) {
            errorreturn("Item not found.");
        }

        // Check if another product with the same name exists in a different category
        $sql_check_duplicate = "SELECT id FROM product_items WHERE institution_id = ? AND product_name = ? AND id != ?";
        $stmt_check_duplicate = $conn_rjllearning_specific->prepare($sql_check_duplicate);
        $stmt_check_duplicate->execute([$institution_id, $product_name, $product_id]);

        if ($stmt_check_duplicate->rowCount() > 0) {
            errorreturn("A product with the same name already exists.");
        }

        // Update the product
        $sql_update = "UPDATE product_items SET product_name = ?, category_id = ?, can_repeat = ?, item_code = ?, send_otp = ?, sale_distribute = ?, 
                       price = ?, last_modified_by = ?, last_modified_at = ? WHERE institution_id = ? AND id = ?";
        $stmt_update = $conn_rjllearning_specific->prepare($sql_update);
        $stmt_update->execute([
            $product_name,
            $category_id,
            $can_repeat,
            $item_code,
            $send_otp,
            $sale_distribute,
            $price,
            $username,
            date('Y-m-d H:i:s'),
            $institution_id,
            $product_id
        ]);

        successreturn([
            'id' => $product_id,
            'successmsg' => "Product updated successfully."
        ]);
    } catch (Exception $e) {
        errorreturn("Error: " . $e->getMessage());
    }
}
