<?php
// api/admin.php
require_once __DIR__ . '/db.php';
session_start();

header('Content-Type: application/json');

function sendResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data);
    exit;
}

if (!isset($_SESSION['user_id'])) {
    sendResponse(['error' => 'Unauthorized. Please login.'], 401);
}

$db = Database::getInstance()->getConnection();

// Check if current user is an admin
$stmtCheckAdmin = $db->prepare('SELECT role FROM users WHERE id = ?');
$stmtCheckAdmin->execute([$_SESSION['user_id']]);
$currentUser = $stmtCheckAdmin->fetch();

if (!$currentUser || $currentUser['role'] !== 'admin') {
    sendResponse(['error' => 'Forbidden. Admin access required.'], 403);
}

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

// Utility route router
$action = isset($_GET['action']) ? $_GET['action'] : ($input['action'] ?? '');

if ($method === 'GET') {
    if ($action === 'users') {
        // List all users
        $stmt = $db->prepare('SELECT id, username, email, role, created_at, is_active FROM users ORDER BY created_at DESC');
        $stmt->execute();
        $users = $stmt->fetchAll();
        sendResponse(['users' => $users]);
    } 
    elseif ($action === 'pending_users_count') {
        $stmt = $db->prepare('SELECT COUNT(id) as count FROM users WHERE is_active = 0');
        $stmt->execute();
        $result = $stmt->fetch();
        sendResponse(['count' => (int)$result['count']]);
    }
    elseif ($action === 'user_boards' && isset($_GET['user_id'])) {
        // List ALL boards so admin can transfer ownership of ANY board to this user
        $userId = intval($_GET['user_id']);
        $stmt = $db->prepare('
            SELECT b.id, b.title, COALESCE(bm.role, "none") as role 
            FROM boards b
            LEFT JOIN board_members bm ON b.id = bm.board_id AND bm.user_id = ?
            ORDER BY b.title ASC
        ');
        $stmt->execute([$userId]);
        $boards = $stmt->fetchAll();
        sendResponse(['boards' => $boards]);
    }
    elseif ($action === 'check_sole_owner' && isset($_GET['user_id'])) {
        $userId = intval($_GET['user_id']);
        
        // Find boards where this user is the only owner
        $stmtBoards = $db->prepare('
            SELECT b.id, b.title 
            FROM boards b
            JOIN board_members bm ON b.id = bm.board_id
            WHERE bm.user_id = ? AND bm.role = "owner"
            AND (
                SELECT COUNT(*) FROM board_members bm2 
                WHERE bm2.board_id = b.id AND bm2.role = "owner" AND bm2.user_id != ?
            ) = 0
        ');
        $stmtBoards->execute([$userId, $userId]);
        $soleOwnedBoards = $stmtBoards->fetchAll(PDO::FETCH_ASSOC);

        // Fetch active users to use as candidates for transferring ownership
        $stmtUsers = $db->prepare('SELECT id, username FROM users WHERE is_active = 1 AND id != ? ORDER BY username ASC');
        $stmtUsers->execute([$userId]);
        $users = $stmtUsers->fetchAll(PDO::FETCH_ASSOC);

        sendResponse([
            'sole_owned_boards' => $soleOwnedBoards,
            'transfer_candidates' => $users
        ]);
    }
    else {
        sendResponse(['error' => 'Invalid admin GET action.'], 400);
    }
} 
elseif ($method === 'PUT') {
    if ($action === 'toggle_active') {
        $userId = $input['user_id'] ?? null;
        $isActive = isset($input['is_active']) ? (int)$input['is_active'] : null;
        
        if (!$userId || $isActive === null) sendResponse(['error' => 'Missing parameters.'], 400);
        if ($userId == $_SESSION['user_id']) sendResponse(['error' => 'Cannot deactivate yourself.'], 400);

        try {
            $stmt = $db->prepare('UPDATE users SET is_active = ? WHERE id = ?');
            $stmt->execute([$isActive, $userId]);
        } catch (Exception $e) {
            sendResponse(['error' => 'Database error: ' . $e->getMessage()], 500);
        }
        
        // Let's also enforce immediate logout for deactivated users by wiping sessions, if possible natively in PHP.
        // For our simple architecture, they will be blocked on their next API request if we verify `is_active` in all endpoints.
        // We will update auth.php to prevent login.
        
        sendResponse(['message' => 'User activation status updated.']);
    }
    elseif ($action === 'change_password') {
        $userId = $input['user_id'] ?? null;
        $newPassword = $input['new_password'] ?? '';
        
        if (!$userId || empty($newPassword)) sendResponse(['error' => 'Missing parameters.'], 400);
        if (strlen($newPassword) < 6) sendResponse(['error' => 'Password too short.'], 400);

        $hash = password_hash($newPassword, PASSWORD_DEFAULT);
        try {
            $stmt = $db->prepare('UPDATE users SET password_hash = ? WHERE id = ?');
            $stmt->execute([$hash, $userId]);
            sendResponse(['message' => 'User password updated.']);
        } catch (Exception $e) {
            sendResponse(['error' => 'Database error: ' . $e->getMessage()], 500);
        }
    }
    elseif ($action === 'change_board_owner') {
        $boardId = $input['board_id'] ?? null;
        $newOwnerUserId = $input['new_owner_user_id'] ?? null;

        if (!$boardId || !$newOwnerUserId) sendResponse(['error' => 'Missing parameters.'], 400);

        try {
            $db->beginTransaction();

            // First, downgrade current owners of this board to editors (usually only 1, but we degrade all just in case)
            $stmtDowngrade = $db->prepare('UPDATE board_members SET role = "editor" WHERE board_id = ? AND role = "owner"');
            $stmtDowngrade->execute([$boardId]);

            // Now set the new owner. They must already be a member of the board.
            // If they are not a member yet, we add them as owner.
            $stmtCheck = $db->prepare('SELECT role FROM board_members WHERE board_id = ? AND user_id = ?');
            $stmtCheck->execute([$boardId, $newOwnerUserId]);
            $exists = $stmtCheck->fetch();

            if ($exists) {
                // Update existing member to owner
                $stmtSet = $db->prepare('UPDATE board_members SET role = "owner" WHERE board_id = ? AND user_id = ?');
                $stmtSet->execute([$boardId, $newOwnerUserId]);
            } else {
                // Add new owner member
                $stmtAdd = $db->prepare('INSERT INTO board_members (board_id, user_id, role) VALUES (?, ?, "owner")');
                $stmtAdd->execute([$boardId, $newOwnerUserId]);
            }

            // Update board's created_by metadata optionally
            $stmtBoard = $db->prepare('UPDATE boards SET created_by = ? WHERE id = ?');
            $stmtBoard->execute([$newOwnerUserId, $boardId]);

            $db->commit();
            sendResponse(['message' => 'Board ownership transferred successfully.']);
        } catch (Exception $e) {
            $db->rollBack();
            sendResponse(['error' => 'Failed to transfer ownership.'], 500);
        }
    }
    elseif ($action === 'change_username') {
        $userId = $input['user_id'] ?? null;
        $newUsername = trim($input['new_username'] ?? '');

        if (!$userId || empty($newUsername)) sendResponse(['error' => 'Missing parameters.'], 400);
        if (strlen($newUsername) < 3) sendResponse(['error' => 'Username must be at least 3 characters.'], 400);

        // Check if username already exists for another user
        $stmtCheck = $db->prepare('SELECT id FROM users WHERE username = ? AND id != ?');
        $stmtCheck->execute([$newUsername, $userId]);
        if ($stmtCheck->fetch()) {
            sendResponse(['error' => 'Username is already taken by another user.'], 400);
        }

        try {
            $stmt = $db->prepare('UPDATE users SET username = ? WHERE id = ?');
            $stmt->execute([$newUsername, $userId]);
            sendResponse(['message' => 'Username updated successfully.']);
        } catch (Exception $e) {
            sendResponse(['error' => 'Database error: ' . $e->getMessage()], 500);
        }
    }
    else {
        sendResponse(['error' => 'Invalid admin PUT action.'], 400);
    }
}
elseif ($method === 'DELETE') {
    if ($action === 'delete_user') {
        $userId = $input['user_id'] ?? null;
        $newOwnerId = $input['new_owner_id'] ?? null;
        
        if (!$userId) sendResponse(['error' => 'Missing User ID.'], 400);
        if ($userId == $_SESSION['user_id']) sendResponse(['error' => 'Cannot delete yourself.'], 400);

        try {
            $db->beginTransaction();

            // Prevent cascade deletion of entire boards or tasks by transferring creator ownership.
            $fallbackOwnerId = $newOwnerId ? $newOwnerId : $_SESSION['user_id'];
            
            $stmtReassignBoards = $db->prepare('UPDATE boards SET created_by = ? WHERE created_by = ?');
            $stmtReassignBoards->execute([$fallbackOwnerId, $userId]);
            
            $stmtReassignTasks = $db->prepare('UPDATE tasks SET created_by = ? WHERE created_by = ?');
            $stmtReassignTasks->execute([$fallbackOwnerId, $userId]);

            if ($newOwnerId) {
                // Find boards where the deleted user is the only owner
                $stmtBoards = $db->prepare('
                    SELECT b.id 
                    FROM boards b
                    JOIN board_members bm ON b.id = bm.board_id
                    WHERE bm.user_id = ? AND bm.role = "owner"
                    AND (
                        SELECT COUNT(*) FROM board_members bm2 
                        WHERE bm2.board_id = b.id AND bm2.role = "owner" AND bm2.user_id != ?
                    ) = 0
                ');
                $stmtBoards->execute([$userId, $userId]);
                $boardsToTransfer = $stmtBoards->fetchAll(PDO::FETCH_COLUMN);

                foreach ($boardsToTransfer as $boardId) {
                    // Check if the new owner is already a member
                    $stmtCheck = $db->prepare('SELECT role FROM board_members WHERE board_id = ? AND user_id = ?');
                    $stmtCheck->execute([$boardId, $newOwnerId]);
                    $exists = $stmtCheck->fetch();

                    if ($exists) {
                        $stmtUpdate = $db->prepare('UPDATE board_members SET role = "owner" WHERE board_id = ? AND user_id = ?');
                        $stmtUpdate->execute([$boardId, $newOwnerId]);
                    } else {
                        $stmtIns = $db->prepare('INSERT INTO board_members (board_id, user_id, role) VALUES (?, ?, "owner")');
                        $stmtIns->execute([$boardId, $newOwnerId]);
                    }

                    // Update board metadata
                    $stmtUpdateBoard = $db->prepare('UPDATE boards SET created_by = ? WHERE id = ?');
                    $stmtUpdateBoard->execute([$newOwnerId, $boardId]);
                }
            }

            // Deleting user will cascade delete their remaining memberships, tasks, etc.
            $stmt = $db->prepare('DELETE FROM users WHERE id = ?');
            $stmt->execute([$userId]);
            
            $db->commit();
            sendResponse(['message' => 'User completely deleted.']);
        } catch (Exception $e) {
            $db->rollBack();
            sendResponse(['error' => 'Failed to delete user: ' . $e->getMessage()], 500);
        }
    }
    else {
        sendResponse(['error' => 'Invalid admin DELETE action.'], 400);
    }
}
else {
    sendResponse(['error' => 'Invalid method.'], 405);
}
