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

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

// Validation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . '/user_management/check_username_availability.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 . 'functions/common_functions.php';


// Fetch and decode input data
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

// Check required fields
if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['branch_id']) || !checkIfIssetAndNotEmpty($postdata['branch_id']) ||
    !isset($postdata['vendor_name']) || !checkIfIssetAndNotEmpty($postdata['vendor_name']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All required fields must be provided.");
}

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 = $postdata['institution_id'];
$branch_id = $postdata['branch_id'];
$ledger_name = ucwords($postdata['ledger_name']);
$ledger_service = $postdata['ledger_service'];
$contact_number = isset($postdata['contact_number']) && !is_null($postdata['contact_number']) ? trim($postdata['contact_number']) : null;
$email = isset($postdata['email']) && !is_null($postdata['email']) ? trim($postdata['email']) : null;
$address = isset($postdata['address']) && !is_null($postdata['address']) ? trim($postdata['address']) : null;
$pincode = isset($postdata['pincode']) && !is_null($postdata['pincode']) ? trim($postdata['pincode']) : null;
$pan = isset($postdata['pan']) && !is_null($postdata['pan']) ? trim($postdata['pan']) : null;
$gst = isset($postdata['gst']) && !is_null($postdata['gst']) ? trim($postdata['gst']) : null;



$ledger_parent_group = trim($postdata['ledger_parent_group']);
$ledger_main_ledgerhead = trim($postdata['ledger_main_ledgerhead']);
$balances = isset($postdata['balances']) ? $postdata['balances'] : [];
$opening_balance = isset($balances['ledger_opening_balance']) ? trim($balances['ledger_opening_balance']) : '0.00';
$opening_balance_type = isset($balances['opening_balance_type']) ? trim($balances['opening_balance_type']) : 'dr';
$current_balance = isset($balances['ledger_current_balance']) ? trim($balances['ledger_current_balance']) : '0.00';
$current_balance_type = isset($balances['current_balance_type']) ? trim($balances['current_balance_type']) : 'dr';


// Validation
if (!checkOnlyCharacters($ledger_name)) {
    errorreturn('ledger Name must contain only letters!');
}

if (!CheckEMailIsValidOrNot($email)) {
    errorreturn('Enter a valid Email Id.');
}

if (strlen($contact_number) != 12 || !is_numeric($contact_number)) {
    errorreturn('Enter a valid 12-digit mobile number.');
}

if (!CheckAddressValidation($address)) {
    errorreturn('Invalid Address.');
}

if (!PinCodeValidation($pincode)) {
    errorreturn('Invalid Pin Code.');
}

if ($gst !== null && !BranchGstValidation($gst)) {
    errorreturn('Invalid GST Number.');
}

if ($pan !== null && !CheckCompanyPanValidtion($pan)) {
    errorreturn("Invalid PAN number.");
}

// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

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

// Create vendor logic
if ($postdata['function_type'] == 'create_act_ledgers') {
    // Check if the vendor already exists
    $check_vendor_sql = "SELECT id FROM act_ledgers WHERE institution_id = ? AND branch_id = ? AND ledger_name = ?";
    $stmt = $conn_rjllearning_specific->prepare($check_vendor_sql);
    $stmt->execute([$institution_id, $branch_id, $ledger_name]);
    
    $existing_vendor = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($existing_vendor) {
        errorreturn("ledger name already exists.");
    }

    // Insert new vendor
    $insert_vendor_sql = "INSERT INTO act_ledgers (
        institution_id, branch_id, vendor_name,vendor_service, contact_number, email, address, pincode, pan, gst, created_by, date_created, time_created, status
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?)";

    $stmt = $conn_rjllearning_specific->prepare($insert_vendor_sql);
    $stmt->execute([
        $institution_id,
        $branch_id,
        $vendor_name,
        $vendor_service,
        $contact_number,
        $email,
        $address,
        $pincode,
        $pan,
        $gst,
        $username,
        date('Y-m-d'),
        date('H:i:s'),
        1
    ]);

    $vendor_id = $conn_rjllearning_specific->lastInsertId();
    successreturn(['id' => $vendor_id, 'successmsg' => "Vendor successfully added."]);

    
}else if ($postdata['function_type'] == 'delete_act_ledgers') {
    // Ensure stop_id is provided
    if (empty($postdata['vendor_id'])) {
        errorreturn("vendor ID is required for deletion.");
    }

    $vendor_id = $postdata['vendor_id'];

    // Check if the stop exists based on stop_id
    $check_stop_sql = "SELECT id FROM vendor WHERE id = ? and institution_id=?";
    $stmt = $conn_rjllearning_specific->prepare($check_stop_sql);
    $stmt->execute([$vendor_id,$institution_id]);

    $existing_stop = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existing_stop) {
        // Delete the existing stop
        $delete_stop_sql = "DELETE FROM vendor WHERE id = ? and institution_id=?";
        $stmt = $conn_rjllearning_specific->prepare($delete_stop_sql);
        $stmt->execute([$vendor_id,$institution_id]);

        successreturn(['successmsg' => "Successfully deleted vendor."]);
    } else {
        errorreturn("vendor ID does not exist.");
    }
} else if ($postdata['function_type'] == 'alter_vendor') {
    // Check if the vendor ID is provided
    if (empty($postdata['vendor_id'])) {
        errorreturn("Vendor ID is required for updating.");
    }
    
    $vendor_id = $postdata['vendor_id'];
    // Check if the vendor exists
    $check_vendor_sql = "SELECT id FROM vendor WHERE id = ? AND institution_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($check_vendor_sql);
    $stmt->execute([$vendor_id, $institution_id]);

    $existing_vendor = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existing_vendor) {
        // Update the vendor details
        $update_vendor_sql = "UPDATE vendor
            SET vendor_name = ?, vendor_service = ?, contact_number = ?, email = ?, address = ?, pincode = ?, pan = ?, gst = ?
            WHERE id = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($update_vendor_sql);
        $stmt->execute([
            $vendor_name,
            $vendor_service,
            $contact_number,
            $email,
            $address,
            $pincode,
            $pan,
            $gst,
            $vendor_id,
            $institution_id
        ]);

        successreturn(['successmsg' => "Vendor details successfully updated."]);
    } else {
        errorreturn("Vendor ID does not exist.");
    }
}
