<?php 
session_start(); 
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user']['id'])) {
    echo json_encode([
        "code" => "error",
        "message" => "Unauthorized access. Please login."
    ]);
    exit();
}

require "../config/db_connect.php";

// Validate required fields
if (!isset($_POST['user_id'], $_POST['shop_id'], $_POST['role'])) {
    echo json_encode([
        "code" => "error",
        "message" => "Missing required fields"
    ]);
    exit();
}

$user_id = intval($_POST['user_id']);
$shop_id = intval($_POST['shop_id']);
$role = trim($_POST['role']);
$current_user = $_SESSION['user']['id'];

// Validate inputs
if ($user_id <= 0 || $shop_id <= 0 || empty($role)) {
    echo json_encode([
        "code" => "error",
        "message" => "Invalid input data"
    ]);
    exit();
}

// Check if user exists
$checkUser = $pdo->prepare("SELECT id, username FROM users WHERE id = ?");
$checkUser->execute([$user_id]);
$user = $checkUser->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode([
        "code" => "error",
        "message" => "User with ID $user_id not found"
    ]);
    exit();
}

// Check if shop exists
$checkShop = $pdo->prepare("SELECT id, name FROM shops WHERE id = ? AND is_active = 1");
$checkShop->execute([$shop_id]);
$shop = $checkShop->fetch(PDO::FETCH_ASSOC);

if (!$shop) {
    echo json_encode([
        "code" => "error",
        "message" => "Shop with ID $shop_id not found or inactive"
    ]);
    exit();
}

// Validate role
$validRoles = ['admin', 'pharmacist', 'cashier'];
if (!in_array($role, $validRoles)) {
    echo json_encode([
        "code" => "error",
        "message" => "Invalid role selected. Must be one of: " . implode(', ', $validRoles)
    ]);
    exit();
}

// Optional: Check if current user has permission (e.g., only admin can assign)
// You can comment this out if you want anyone to be able to assign
/*
$checkPermission = $pdo->prepare("SELECT role FROM users WHERE id = ?");
$checkPermission->execute([$current_user]);
$currentUserRole = $checkPermission->fetchColumn();

if ($currentUserRole !== 'admin') {
    echo json_encode([
        "code" => "error",
        "message" => "You don't have permission to assign users"
    ]);
    exit();
}
*/

// Try to assign user with error handling
try {
    $pdo->beginTransaction();
    
    $assign = $pdo->prepare("UPDATE users SET role = ?, shop_id = ? WHERE id = ?");
    
    if ($assign->execute([$role, $shop_id, $user_id])) {
        $rowsAffected = $assign->rowCount();
        
        $pdo->commit();
        
        echo json_encode([
            "code" => "success",
            "message" => "User '{$user['username']}' assigned to shop '{$shop['name']}' with role '$role'",
            "rows_affected" => $rowsAffected
        ]);
    } else {
        $pdo->rollBack();
        echo json_encode([
            "code" => "error",
            "message" => "Failed to execute update query"
        ]);
    }
    
} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    // More specific error messages
    $errorCode = $e->getCode();
    $errorMessage = $e->getMessage();
    
    if ($errorCode == 23000) { // Foreign key constraint violation
        echo json_encode([
            "code" => "error",
            "message" => "Foreign key constraint violation. Shop ID $shop_id might not exist or there's a constraint issue."
        ]);
    } else if (strpos($errorMessage, 'shop_id') !== false) {
        echo json_encode([
            "code" => "error",
            "message" => "Shop constraint error: " . $errorMessage
        ]);
    } else {
        // Log the full error for debugging
        error_log("Assign user error [Code: $errorCode]: " . $errorMessage);
        
        echo json_encode([
            "code" => "error",
            "message" => "Database error: " . (strpos($errorMessage, 'shop_id') !== false ? 
                          "Invalid shop ID or constraint violation" : 
                          "Please try again or contact administrator")
        ]);
    }
}
?>