<?php
require_once '../auth_helper.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $userId = $_POST['id'];
    $name = $_POST['name'];
    $email = $_POST['email'];
    $role = $_POST['role'];
    $password = $_POST['password'] ?? '';
    $pdo = db();

    try {
        $stmt = $pdo->prepare("SELECT email, supabase_uid FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $userRecord = $stmt->fetch();

        if (!empty($password)) {
            // Update Supabase password
            if ($userRecord && $userRecord['supabase_uid']) {
                SupabaseAuth::updateUserPassword($userRecord['supabase_uid'], $password);
            }

            $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, role = ? WHERE id = ?");
            $stmt->execute([$name, $email, $role, $userId]);
        } else {
            $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, role = ? WHERE id = ?");
            $stmt->execute([$name, $email, $role, $userId]);
        }

        $currentUser = get_user();
        audit_log('officer_updated', 'users', $userId, null, null, "Updated officer ID $userId info");

        header("Location: ../officers_management.php?success=officer_updated");
        exit;
    } catch (PDOException $e) {
        die("Error updating officer: " . $e->getMessage());
    }
} else {
    header("Location: ../officers_management.php");
    exit;
}
