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

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


// 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'];
$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);
$branch_id = $postdata['branch_id'];
$vendor_name = ucwords($postdata['vendor_name']);

$amount = $postdata['amount'];
$expense_id = $postdata['expense_id'] ?? null;
$date = $postdata['date'];
$transaction_reference_id = $postdata['transaction_reference_id'];
$transaction_type_group = $postdata['transaction_type_group'] ?? null;

if (!in_array($transaction_type_group, ['expense', 'receipt'])) {
   
    errorreturn("Invalid transaction type group. It must be 'expense' or 'receipt'.");
}

// Proceed with valid $transaction_type_group

$payment_bool = isset($postdata['payment_bool']) ? $postdata['payment_bool'] : 0; // 1 for paid, 0 for unpaid

// Define allowed payment methods
$allowed_payment_methods = [
    'cheque', 
    'upi', 
    'credit_card', 
    'debit_card', 
    'internet_banking', 
    'qr_code', 
    'cash', 
    'others'
];

$paid_on = isset($postdata['paid_on']) ? $postdata['paid_on'] : date('Y-m-d');

// Ensure payment_method is formatted using ucwords
$payment_method = isset($postdata['payment_method']) && $postdata['payment_method'] !== '' 
    ? $postdata['payment_method'] 
    : null;



if (!in_array($payment_method, $allowed_payment_methods, true) and $payment_method !=null) {
    errorreturn("Invalid payment_method. Allowed values are: " . implode(', ', $allowed_payment_methods) . ".");
}

$remarks = ucwords($postdata['remarks']) ?? null;
$recorded_in_finware = isset($postdata['recorded_in_finware']) ? $postdata['recorded_in_finware'] : 0;
// $expense_type = isset($postdata['expense_type']) ? $postdata['expense_type'] : null;
$category_id = $postdata['category_id'] ?? null; // Default to null if not provided
$attachment = (isset($_FILES['attachment']) and !empty($_FILES['attachment'])) ? $_FILES['attachment'] : null;
if (empty($category_id)) {
    errorreturn("No expense ID provided.");
}

// Prepare the query to check if the expense ID exists in act_ledger_group
$check_expense_sql = "SELECT id FROM unmarked_transaction_type_group WHERE group_name = ? AND institution_id = ? ";
$insert_expense_sql = "INSERT INTO unmarked_transaction_type_group (institution_id, group_name, created_by, date_created, time_created, status) VALUES ( ?, ?, ?, ?, ?, ?)";
$fetch_new_id_sql = "SELECT id FROM unmarked_transaction_type_group WHERE group_name = ? AND institution_id = ? ";

$stmt = $conn_rjllearning_specific->prepare($check_expense_sql);
$stmt->execute([$category_id, $institution_id]);

if ($stmt->rowCount() > 0) {
    // If the record exists, fetch the existing id
    $existing_record = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($existing_record && isset($existing_record['id'])) {
        $existing_id = $existing_record['id'];
    } else {
        errorreturn("Failed to retrieve the existing record ID.");
    }
} else {
    // If not exists, insert the new expense_id
    $stmt_insert = $conn_rjllearning_specific->prepare($insert_expense_sql);
    $stmt_insert->execute([$institution_id, $expense_id, $username, date('Y-m-d'), time(), 0]);

    // Fetch the new id after insertion
    $stmt_fetch = $conn_rjllearning_specific->prepare($fetch_new_id_sql);
    $stmt_fetch->execute([$expense_id, $institution_id]);
    $new_record = $stmt_fetch->fetch(PDO::FETCH_ASSOC);
    if ($new_record && isset($new_record['id'])) {
        $existing_id = $new_record['id'];
    } else {
        errorreturn("Failed to retrieve the newly inserted record ID.");
    }
}





// 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_unmarked_expense_transaction') {
    // // Check if the vendor already exists
    // $check_vehicle_expense_sql = "SELECT id FROM unmarked_transaction WHERE institution_id = ? AND branch_id = ? AND vendor_name = ?";
    // $stmt = $conn_rjllearning_specific->prepare($check_vehicle_expense_sql);
    // $stmt->execute([$institution_id, $branch_id, $vendor_name]);
    
    // $existing_vendor = $stmt->fetch(PDO::FETCH_ASSOC);
    // if ($existing_vendor) {
    //     errorreturn("Vendor name already exists.");
    // }
      if ($attachment == null) {
        $attachment = null;
    } else {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $currentDay =  date('d');

        $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/unmarked_expense_transaction/" . $currentYear . "/" . $currentMonth . "/";
        
        $file_name = $_FILES['attachment']['name'];
        $fileTmpName = $_FILES['attachment']["tmp_name"];
        $fileSize = $_FILES['attachment']["size"];
        $fileType = $_FILES['attachment']["type"];
        $fileError = $_FILES['attachment']["error"];
        $file_extension = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = [
            'image/jpeg', 'image/png', 'image/gif', 'image/heic', 'application/pdf', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel',
            'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ]; // Allowed image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
        $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }
    
    // Insert new vendor
    $insert_transaction_sql = "INSERT INTO unmarked_transaction (institution_id, branch_id, vendor_name, category_id, amount, date, transaction_reference_id, payment_bool, payment_method, paid_on, attachment, remarks, created_by, date_created, time_created, last_edit, last_edit_at, approved_by, recorded_in_finware, transaction_type_group, status
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn_rjllearning_specific->prepare($insert_transaction_sql);
    $stmt->execute([$institution_id,$branch_id,$vendor_name,$existing_id,$amount,$date,$transaction_reference_id,$payment_bool,$payment_method,$paid_on,null,$remarks,$username,date('Y-m-d'),time(),null,null,null,0,$transaction_type_group,1
    ]);

    $vehicle_expense_id = $conn_rjllearning_specific->lastInsertId();
    
    if ($attachment !=  null) {
        $image_name = "unmarked_transaction_" . $vehicle_expense_id . "." . $file_extension; // Define the image name dynamically
        $path = $directoryPathMain . $image_name; // Create the full path for the logo
        awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $attachment, $path, $multiple_files_bool = false, $multiple_file_index = 0);
        $attachment_image = json_encode(array("filepath" => $path, "original_name" => $file_name));
        $sql_logo = "UPDATE unmarked_transaction SET attachment = ? WHERE id= ?";
        $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $vehicle_expense_id));
    }
    
    successreturn(['id' => $vehicle_expense_id, 'successmsg' => "vehicle expense successfully added."]);

    
} else if ($postdata['function_type'] == 'alter_unmarked_expense_transaction') {
    // Check if the expense ID is provided
    if (empty($postdata['expense_id'])) {
        errorreturn("Expense ID is required for updating.");
    }

    $expense_id = $postdata['expense_id'];
    $remove_bool = isset($postdata['remove_bool']) && !empty($postdata['remove_bool']) ? trim($postdata['remove_bool']) : 0;

    // Check if the expense exists
    $res = $conn_rjllearning_specific->prepare("SELECT attachment FROM unmarked_transaction WHERE id = ? AND institution_id = ? AND branch_id = ?");
    $res->execute([$expense_id, $institution_id, $branch_id]);
    $result1 = $res->fetch(PDO::FETCH_ASSOC);

    if (!$result1) {
        errorreturn("Expense does not exist.");
    }

    $existing_attachment = $result1['attachment'];
    if($existing_attachment !=  null){
            $data_attachment = json_decode($existing_attachment, true);
            $filePath = $data_attachment['filepath'];
    }
    if ($remove_bool == 1 && isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/unmarked_expense_transaction/" . $currentYear . "/" . $currentMonth . "/";
    
        $file_name = $_FILES['attachment']['name'];
        $fileTmpName = $_FILES['attachment']['tmp_name'];
        $fileType = $_FILES['attachment']['type'];
        $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // File validation
        $allowedTypes = [
            'image/jpeg', 'image/png', 'image/gif', 'image/heic', 'application/pdf', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel',
            'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ];
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
        $maxFileSize = 2 * 1024 * 1024; // 2MB

        checkFileValidation(filesize($fileTmpName), $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }
    
    // Fetch the category_id of the stored record
        $check_vendor_sql = "SELECT category_id FROM unmarked_transaction WHERE id = ? AND institution_id = ? AND branch_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($check_vendor_sql);
        $stmt->execute([$expense_id, $institution_id, $branch_id]);
        $stored_category = $stmt->fetch();
        
        if (!$stored_category) {
            errorreturn("Category Info not exists.");
        }
        
        $stored_group_id = $stored_category['category_id'];
        
        // Fetch stored group details
        $sql_stored = "SELECT id, group_name, main_ledgerhead FROM unmarked_transaction_type_group WHERE id = ? AND institution_id = ?";
        $stmt_stored = $conn_rjllearning_specific->prepare($sql_stored);
        $stmt_stored->execute([$stored_group_id, $institution_id]);
        $stored_group = $stmt_stored->fetch();
        
        if (!$stored_group) {
            errorreturn("Stored group info not exists.");
        }
        
        $stored_group_name = strtolower($stored_group['group_name']);
        $stored_main_ledgerhead = strtolower($stored_group['main_ledgerhead']);
        
        // Fetch the incoming group details
        $sql_incoming = "SELECT id, group_name, main_ledgerhead FROM unmarked_transaction_type_group WHERE id = ? AND institution_id = ?";
        $stmt_incoming = $conn_rjllearning_specific->prepare($sql_incoming);
        $stmt_incoming->execute([$existing_id, $institution_id]);
        $incoming_group = $stmt_incoming->fetch();
        
        if (!$incoming_group) {
            errorreturn("Incoming group info not exists.");
        }
        
        $incoming_group_name = strtolower($incoming_group['group_name']);
        $incoming_main_ledgerhead = strtolower($incoming_group['main_ledgerhead']);
        
        // Logic to allow or restrict updates
        if (
            ($stored_group_name === "transport" && $incoming_group_name !== "transport") ||
            ($stored_group_name === "student_registration" && $incoming_group_name !== "student_registration")
        ) {
            errorreturn("Updates are only allowed for 'Transport' and 'Student_Registration' within the same group.");
        }
        
        // If all conditions pass, update is allowed


    // Check if the vendor exists and proceed with update
    $check_vendor_sql = "SELECT id FROM unmarked_transaction WHERE id = ? AND institution_id = ? AND branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($check_vendor_sql);
    $stmt->execute([$expense_id, $institution_id, $branch_id]);

    if ($stmt->rowCount() > 0) {
        // Update the vendor details
        $update_vendor_sql = "UPDATE unmarked_transaction SET vendor_name = ?, category_id = ?, amount = ?, date = ?, transaction_reference_id = ?, payment_bool = ?, payment_method = ?, paid_on = ?,
             remarks = ?, last_edit = ?, last_edit_at = ?,
            approved_by = ?, recorded_in_finware = ?, transaction_type_group = ?, status = ?
            WHERE id = ? AND institution_id = ? AND branch_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($update_vendor_sql);
        $stmt->execute([$vendor_name,$existing_id,$amount,$date,$transaction_reference_id,$payment_bool,$payment_method,$paid_on,$remarks,date('Y-m-d'),time(),$username,$recorded_in_finware,$transaction_type_group,1,$expense_id,$institution_id,$branch_id
        ]);
        
   if ($remove_bool == 1 && $existing_attachment !== null) {
        // Delete the existing attachment from S3
        awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $filePath, null, null);
        // Remove the attachment path from the database
        $sql = "UPDATE unmarked_transaction SET attachment = NULL WHERE id = ? AND institution_id = ?";
        $conn_rjllearning_specific->prepare($sql)->execute([$expense_id, $institution_id]);
    }
     
    if ($attachment !=  null) {
        $image_name = "unmarked_transaction_" . $expense_id . "." . $file_extension; // Define the image name dynamically
        $path = $directoryPathMain . $image_name; // Create the full path for the logo
        awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $attachment, $path, $multiple_files_bool = false, $multiple_file_index = 0);
        $attachment_image = json_encode(array("filepath" => $path, "original_name" => $file_name));
        $sql_logo = "UPDATE unmarked_transaction SET attachment = ? WHERE id= ? AND institution_id = ? ";
        $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $expense_id,$institution_id));
    }   

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