<?php
// test_update.php
require_once '../config/db_connect.php';

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
    // Test with user ID 2
    $user_id = 2;
    $shop_id = 1; // Make sure this shop exists
    $role = 'pharmacist';
    
    echo "<h3>Testing User Update</h3>";
    
    // Get current data
    $stmt = $pdo->prepare("SELECT id, username, shop_id, role FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $current = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo "<p><strong>Current Data:</strong><br>";
    echo "ID: " . $current['id'] . "<br>";
    echo "Username: " . $current['username'] . "<br>";
    echo "Shop ID: " . $current['shop_id'] . "<br>";
    echo "Role: " . $current['role'] . "</p>";
    
    // Update
    $update_sql = "UPDATE users SET shop_id = ?, role = ? WHERE id = ?";
    $update_stmt = $pdo->prepare($update_sql);
    $update_stmt->execute([$shop_id, $role, $user_id]);
    
    echo "<p><strong>Update Result:</strong><br>";
    echo "Rows affected: " . $update_stmt->rowCount() . "</p>";
    
    // Get updated data
    $verify_stmt = $pdo->prepare("SELECT id, username, shop_id, role, updated_at FROM users WHERE id = ?");
    $verify_stmt->execute([$user_id]);
    $updated = $verify_stmt->fetch(PDO::FETCH_ASSOC);
    
    echo "<p><strong>Updated Data:</strong><br>";
    echo "ID: " . $updated['id'] . "<br>";
    echo "Username: " . $updated['username'] . "<br>";
    echo "Shop ID: " . $updated['shop_id'] . "<br>";
    echo "Role: " . $updated['role'] . "<br>";
    echo "Updated At: " . $updated['updated_at'] . "</p>";
    
    echo "<hr>";
    
    // Test NULL shop_id
    echo "<h3>Testing NULL Shop ID</h3>";
    $update_stmt2 = $pdo->prepare("UPDATE users SET shop_id = NULL, role = ? WHERE id = ?");
    $update_stmt2->execute(['cashier', $user_id]);
    echo "Rows affected: " . $update_stmt2->rowCount();
    
} catch (PDOException $e) {
    echo "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
}
?>