<?php
require_once "../models/Operations.php";

$sql = "SELECT user_id,user_pos_id FROM tb_users;";
$userInfo = executePDOFetchAll($sql);

// Initialize variables for query construction
$cases = [];
$userIds = [];

foreach ($userInfo as $user) {

    $userId = $user['user_id']; // Collect user_ids for WHERE clause
    $userIds[] = $userId; // Collect user_ids for WHERE clause

    $posInfo = getBranchData($user['user_pos_id']);

    $posAccess = [['pos_id' => $posInfo['pos_id'], 'pos_name' => $posInfo['pos_name']]];
    $posAccessJson = json_encode($posAccess, JSON_PRETTY_PRINT);

    // Create a `CASE` clause for each user
    $cases[] = "WHEN user_id = $userId THEN '$posAccessJson'";
}

// Construct the full `UPDATE` query with `CASE` statements
$caseQuery = implode(" ", $cases);
$userIdsList = implode(",", $userIds);

$sqlUserAccess = "UPDATE tb_users
    SET user_branch_access = CASE
        $caseQuery
    END
    WHERE user_id IN ($userIdsList)
";

$sqlUpdateAllImage = "UPDATE tb_enterprises SET ent_logo = NULL;";
$sqlUpdateAllImage .= "UPDATE tb_products SET pro_image = NULL;";
$sqlUpdateAllImage .= "UPDATE tb_users SET user_image = NULL;";
executeQueryPDO($sqlUpdateAllImage);

// Execute the single query
$answer = executeQueryPDOApi($sqlUserAccess, "UPDATED", "BATCH USERS ACCESS UPDATE");
var_dump($answer);
