<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';
$pdo = getDBConnection();

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['usuario_id']) || !isset($input['sucursales'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

$usuario_id = $input['usuario_id'];
$sucursales = $input['sucursales']; // Array of branch IDs

try {
    $pdo->beginTransaction();

    // 1. Remove current assignments for this user
    $stmtDelete = $pdo->prepare("DELETE FROM usuario_sucursal WHERE usuario_id = ?");
    $stmtDelete->execute([$usuario_id]);

    // 2. Insert new assignments
    if (!empty($sucursales)) {
        $stmtInsert = $pdo->prepare("INSERT INTO usuario_sucursal (usuario_id, sucursal_id, rol, activo) VALUES (?, ?, 'vendedor', 1)");
        foreach ($sucursales as $sucursal_id) {
            $stmtInsert->execute([$usuario_id, $sucursal_id]);
        }
    }

    $pdo->commit();
    echo json_encode(['success' => true, 'message' => 'Assignments updated successfully']);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
