<?php
// GET    /api/users/:id
// PUT    /api/users/:id
// DELETE /api/users/:id
// PATCH  /api/users/:id/status

$id     = (int)($GLOBALS['route_params'][0] ?? 0);
$method = $_SERVER['REQUEST_METHOD'];

if (!$id) {
    sendError('Invalid user ID');
}

$db = getDB();

if ($method === 'GET') {
    $stmt = $db->prepare("SELECT id, name, employee_id, mobile, role, status FROM users WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $db->close();

    if (!$user) sendError('User not found', 404);
    sendSuccess(['data' => $user]);
}

if ($method === 'PUT') {
    $input    = json_decode(file_get_contents('php://input'), true);
    $name     = trim($input['name']     ?? '');
    $mobile   = trim($input['mobile']   ?? '');
    $role     = trim($input['role']     ?? '');
    $password = trim($input['password'] ?? '');

    if (!$name || !$mobile || !$role) {
        sendError('name, mobile and role are required');
    }

    $allowed_roles = ['SUPER_ADMIN', 'EMPLOYEE'];
    if (!in_array($role, $allowed_roles)) sendError('Invalid role');

    if ($password) {
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        $stmt   = $db->prepare("UPDATE users SET name=?, mobile=?, role=?, password=? WHERE id=?");
        $stmt->bind_param("ssssi", $name, $mobile, $role, $hashed, $id);
    } else {
        $stmt = $db->prepare("UPDATE users SET name=?, mobile=?, role=? WHERE id=?");
        $stmt->bind_param("sssi", $name, $mobile, $role, $id);
    }

    if (!$stmt->execute()) sendError('Failed to update user', 500);
    if ($stmt->affected_rows === 0) sendError('User not found', 404);
    $stmt->close();
    $db->close();

    sendSuccess([], 'User updated successfully');
}

if ($method === 'DELETE') {
    // Verify user exists first
    $check = $db->prepare("SELECT id FROM users WHERE id = ?");
    $check->bind_param("i", $id);
    $check->execute();
    $check->get_result()->fetch_assoc() || ($check->close() && $db->close() && sendError('User not found', 404));
    $check->close();

    $db->begin_transaction();

    try {
        // Delete related meter readings first (no cascade defined on FK)
        $stmt = $db->prepare("DELETE FROM meter_readings WHERE user_id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();

        // Delete the user
        $stmt = $db->prepare("DELETE FROM users WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();

        $db->commit();
    } catch (Exception $e) {
        $db->rollback();
        $db->close();
        sendError('Failed to delete user', 500);
    }

    $db->close();
    sendSuccess([], 'User deleted successfully');
}


if ($method === 'PATCH') {
    // PATCH /api/users/:id/status
    $input  = json_decode(file_get_contents('php://input'), true);
    $status = trim($input['status'] ?? '');

    if (!in_array($status, ['ACTIVE', 'INACTIVE'])) {
        sendError('status must be ACTIVE or INACTIVE');
    }

    $stmt = $db->prepare("UPDATE users SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $status, $id);
    $stmt->execute();
    if ($stmt->affected_rows === 0) sendError('User not found', 404);
    $stmt->close();
    $db->close();

    sendSuccess([], 'User status updated successfully');
}

sendError('Method not allowed', 405);
