<?php

declare(strict_types=1);

// api/admin.php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/session_auth.php';

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate');

$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
$pathInfo = isset($_SERVER['PATH_INFO'])
    ? explode('/', trim((string)$_SERVER['PATH_INFO'], '/'))
    : [];

$action = $pathInfo[0] ?? '';
$id = $pathInfo[1] ?? null;

// Read an existing bearer identity so database triggers can record admin API writes.
// The sign-in route has no bearer token yet and is recorded after the new session is committed.
if (!($action === 'login' && $method === 'POST')) {
    rvu_audit_context_from_request($pdo);
}

$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput ?: '', true);
if (!is_array($input)) {
    $input = [];
}

function adminRespond(int $status, array $payload): void
{
    http_response_code($status);
    echo json_encode(
        $payload,
        JSON_UNESCAPED_SLASHES |
            JSON_UNESCAPED_UNICODE |
            JSON_INVALID_UTF8_SUBSTITUTE
    );
    exit;
}

/**
 * Convert the administrator permissions value to a clean JSON array string.
 * Both the admins and users records can therefore carry the same permissions.
 */
function adminNormalizePermissions($value): string
{
    if ($value === null || $value === '') {
        return '[]';
    }

    if (is_array($value)) {
        $clean = [];
        foreach ($value as $item) {
            if (is_string($item) && trim($item) !== '') {
                $clean[] = trim($item);
            }
        }
        return json_encode(array_values(array_unique($clean)));
    }

    if (is_string($value)) {
        $decoded = json_decode($value, true);

        if (is_array($decoded)) {
            $clean = [];
            foreach ($decoded as $item) {
                if (is_string($item) && trim($item) !== '') {
                    $clean[] = trim($item);
                }
            }
            return json_encode(array_values(array_unique($clean)));
        }
    }

    return '[]';
}

/**
 * Campus News and the newer authenticated APIs identify people through the
 * users table. Administrators are still managed in the admins table, so every
 * administrator must also have a companion users row.
 *
 * This method synchronizes the companion users row. A brand-new companion
 * requires NRC because users.nrc is NOT NULL. Existing companion rows can be
 * synchronized during login without overwriting profile fields.
 *
 * The returned integer is the users.id that must be stored in user_sessions.
 */
function adminEnsureCompanionUser(PDO $pdo, array $admin, array $profile = [], ?string $lookupEmail = null): int
{
    $email = trim((string)($admin['email'] ?? ''));
    $name = trim((string)($admin['name'] ?? ''));
    $role = trim((string)($admin['role'] ?? 'Admin'));
    $campus = isset($admin['campus']) ? trim((string)$admin['campus']) : null;
    $passwordHash = (string)($admin['password'] ?? '');
    $permissions = adminNormalizePermissions($admin['permissions'] ?? null);

    if ($email === '' || $name === '' || $passwordHash === '') {
        throw new RuntimeException(
            'The administrator record is missing email, name, or password.'
        );
    }

    // Profile values come from the Flutter provisioning form. Keep them
    // separate from the admins table because users.php owns these columns.
    $profileColumnMap = [
        'phone' => 'phone',
        'nrc' => 'nrc',
        'gender' => 'gender',
        'country' => 'country',
        'school' => 'school',
        'program' => 'program',
        'profile_picture' => 'profile_picture',
    ];

    $normalizedProfile = [];
    foreach ($profileColumnMap as $inputKey => $columnName) {
        if (!array_key_exists($inputKey, $profile)) {
            continue;
        }

        $value = $profile[$inputKey];
        if ($value !== null && !is_string($value) && !is_numeric($value)) {
            throw new InvalidArgumentException(
                'Invalid administrator profile field: ' . $inputKey
            );
        }

        $clean = $value === null ? '' : trim((string)$value);
        $normalizedProfile[$inputKey] = $clean === '' ? null : $clean;
    }

    if (
        array_key_exists('nrc', $normalizedProfile) &&
        $normalizedProfile['nrc'] === null
    ) {
        throw new InvalidArgumentException('NRC / ID Number is required.');
    }

    $stmt = $pdo->prepare(
        'SELECT id
         FROM users
         WHERE LOWER(email) = LOWER(?)
         LIMIT 1'
    );
    $stmt->execute([$email]);
    $existingUserId = $stmt->fetchColumn();

    // When an administrator email is edited, locate the existing companion by
    // the previous email instead of accidentally attempting a second users row.
    if ($existingUserId === false && $lookupEmail !== null) {
        $previousEmail = trim($lookupEmail);
        if ($previousEmail !== '' && strcasecmp($previousEmail, $email) !== 0) {
            $stmt->execute([$previousEmail]);
            $existingUserId = $stmt->fetchColumn();
        }
    }

    if ($existingUserId !== false) {
        $userId = (int)$existingUserId;

        // Always synchronize identity/security fields. Only change companion
        // profile fields when the caller actually supplied them. This prevents
        // admin login from wiping NRC/phone/profile data with NULL values.
        $sets = [
            'full_name = ?',
            'email = ?',
            'password = ?',
            'role = ?',
            'campus = ?',
            'permissions = ?',
        ];
        $params = [
            $name,
            $email,
            $passwordHash,
            $role,
            $campus !== '' ? $campus : null,
            $permissions,
        ];

        foreach ($profileColumnMap as $inputKey => $columnName) {
            if (!array_key_exists($inputKey, $normalizedProfile)) {
                continue;
            }
            $sets[] = $columnName . ' = ?';
            $params[] = $normalizedProfile[$inputKey];
        }

        $params[] = $userId;
        $update = $pdo->prepare(
            'UPDATE users SET ' . implode(', ', $sets) . ' WHERE id = ?'
        );
        $update->execute($params);

        return $userId;
    }

    // A new companion users record cannot be created without NRC because the
    // Rockview users table enforces users.nrc as NOT NULL.
    $nrc = $normalizedProfile['nrc'] ?? null;
    if ($nrc === null) {
        throw new InvalidArgumentException(
            'NRC / ID Number is required when creating an administrator account.'
        );
    }

    $insert = $pdo->prepare(
        'INSERT INTO users (
            full_name,
            email,
            password,
            phone,
            nrc,
            role,
            gender,
            country,
            campus,
            school,
            program,
            permissions,
            profile_picture
         )
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
         RETURNING id'
    );

    $insert->execute([
        $name,
        $email,
        $passwordHash,
        $normalizedProfile['phone'] ?? null,
        $nrc,
        $role,
        $normalizedProfile['gender'] ?? null,
        $normalizedProfile['country'] ?? null,
        $campus !== '' ? $campus : null,
        $normalizedProfile['school'] ?? null,
        $normalizedProfile['program'] ?? null,
        $permissions,
        $normalizedProfile['profile_picture'] ?? null,
    ]);

    $newUserId = $insert->fetchColumn();

    if ($newUserId === false) {
        throw new RuntimeException(
            'Unable to create the administrator companion user record.'
        );
    }

    return (int)$newUserId;
}

/**
 * Fetch a complete administrator row, including password, for server-side
 * synchronization. Password hashes are never returned to Flutter.
 */
function adminFetchById(PDO $pdo, int $adminId): ?array
{
    $stmt = $pdo->prepare(
        'SELECT id, name, email, role, position, campus, permissions, password
         FROM admins
         WHERE id = ?
         LIMIT 1'
    );
    $stmt->execute([$adminId]);

    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

try {
    if (!isset($pdo) || !($pdo instanceof PDO)) {
        throw new RuntimeException('Database connection was not initialized.');
    }

    // ============================================================
    // ADMIN AUTHENTICATION
    // ============================================================
    if ($action === 'login' && $method === 'POST') {
        $email = trim((string)($input['email'] ?? ''));
        $password = (string)($input['password'] ?? '');

        if ($email === '' || $password === '') {
            adminRespond(400, [
                'detail' => 'Email and password are required.',
            ]);
        }

        $stmt = $pdo->prepare(
            'SELECT id, name, email, role, position, campus, permissions, password
             FROM admins
             WHERE LOWER(email) = LOWER(?)
             LIMIT 1'
        );
        $stmt->execute([$email]);

        $admin = $stmt->fetch(PDO::FETCH_ASSOC);

        $safePassword = substr($password, 0, 72);

        if (
            !$admin ||
            !password_verify($safePassword, (string)$admin['password'])
        ) {
            adminRespond(401, [
                'detail' => 'Invalid email or password.',
            ]);
        }

        /*
         * IMPORTANT:
         * The old code returned "mock_jwt_token_...". Campus News cannot
         * validate that token because it never existed in user_sessions.
         *
         * We now:
         *   1. guarantee a matching users record;
         *   2. create a real Rockview server-side session;
         *   3. return the real rvu_session_... token to Flutter.
         */
        $pdo->beginTransaction();

        try {
            $userId = adminEnsureCompanionUser($pdo, $admin);
            rvu_ensure_account_status_columns($pdo);
            $statusStmt = $pdo->prepare("SELECT COALESCE(account_status, 'active') AS account_status, suspension_reason FROM users WHERE id = ? LIMIT 1");
            $statusStmt->execute([$userId]);
            $accountState = $statusStmt->fetch(PDO::FETCH_ASSOC) ?: ['account_status' => 'active'];
            if (strtolower((string)($accountState['account_status'] ?? 'active')) === 'suspended') {
                $pdo->rollBack();
                adminRespond(403, [
                    'detail' => 'This administrator account has been suspended. Contact Rockview University administration.',
                    'account_status' => 'suspended',
                    'reason' => $accountState['suspension_reason'] ?? null,
                ]);
            }
            $token = rvu_issue_session($pdo, $userId);

            $pdo->commit();
            rvu_record_auth_audit($pdo, [
                'id' => $userId,
                'full_name' => (string)$admin['name'],
                'role' => (string)$admin['role'],
                'campus' => (string)($admin['campus'] ?? ''),
            ], 'login', 'Administrator signed in successfully.');
        } catch (Throwable $sessionError) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            throw $sessionError;
        }

        adminRespond(200, [
            'status' => 'success',
            'message' => 'Welcome, Admin!',
            'token' => $token,
            'token_type' => 'bearer',
            'user' => [
                // Use users.id as the authenticated identity because all
                // Campus News relationships reference users.
                'id' => $userId,
                'adminId' => (int)$admin['id'],
                'fullName' => $admin['name'],
                'full_name' => $admin['name'],
                'email' => $admin['email'],
                'role' => $admin['role'],
                'position' => $admin['position'],
                'campus' => $admin['campus'],
                'permissions' => $admin['permissions'] ?? '[]',
            ],
        ]);
    }

    // ============================================================
    // ADMIN LOGOUT
    // ============================================================
    elseif ($action === 'logout' && $method === 'POST') {
        $user = rvu_current_user($pdo);
        if ($user) {
            rvu_record_auth_audit($pdo, $user, 'logout', 'Administrator signed out successfully.');
        }
        rvu_revoke_current_session($pdo);

        adminRespond(200, [
            'status' => 'success',
            'message' => 'Logged out successfully.',
        ]);
    }

    // ============================================================
    // OFFICIAL REQUESTS
    // ============================================================
    elseif ($action === 'requests') {
        if ($method === 'GET') {
            $stmt = $pdo->query(
                'SELECT *
                 FROM official_requests
                 ORDER BY created_at DESC'
            );

            adminRespond(200, [
                'data' => $stmt->fetchAll(PDO::FETCH_ASSOC),
            ]);
        } elseif ($method === 'POST') {
            $sql =
                'INSERT INTO official_requests (
                    recipient_name,
                    sender_name,
                    sender_title,
                    target_campus,
                    reference,
                    title,
                    body_content,
                    body,
                    status,
                    created_at
                 )
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
                 RETURNING id';

            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                $input['recipient_name'] ?? null,
                $input['sender_name'] ?? null,
                $input['sender_title'] ?? null,
                $input['target_campus'] ?? null,
                $input['reference'] ?? null,
                $input['title'] ?? null,
                $input['body_content'] ?? null,
                $input['body'] ?? null,
                'pending',
            ]);

            adminRespond(201, [
                'message' => 'Request dispatched',
                'id' => (int)$stmt->fetchColumn(),
            ]);
        } elseif ($method === 'PUT' && $id !== null) {
            $status = $input['status'] ?? null;
            $comments = $input['admin_comments'] ?? null;
            $recipient = $input['recipient_name'] ?? null;

            if ($status === null || $status === '') {
                adminRespond(400, [
                    'detail' => 'Status is required.',
                ]);
            }

            $sql = 'UPDATE official_requests SET status = ?';
            $params = [$status];

            if ($comments !== null) {
                $sql .= ', admin_comments = ?';
                $params[] = $comments;
            }

            if ($recipient !== null) {
                $sql .= ', recipient_name = ?';
                $params[] = $recipient;
            }

            $sql .= ' WHERE id = ?';
            $params[] = $id;

            $pdo->prepare($sql)->execute($params);

            adminRespond(200, [
                'message' => 'Request updated and routed successfully',
            ]);
        } elseif ($method === 'DELETE' && $id !== null) {
            $pdo->prepare(
                'DELETE FROM official_requests WHERE id = ?'
            )->execute([$id]);

            adminRespond(200, [
                'message' => 'Request deleted',
            ]);
        } else {
            adminRespond(405, [
                'detail' => 'Unsupported official request operation.',
            ]);
        }
    }

    // ============================================================
    // CLUBS
    // ============================================================
    elseif ($action === 'clubs') {
        if ($method === 'GET') {
            adminRespond(
                200,
                $pdo->query('SELECT * FROM clubs')
                    ->fetchAll(PDO::FETCH_ASSOC)
            );
        } elseif (
            $method === 'PUT' &&
            $id !== null &&
            isset($pathInfo[2]) &&
            $pathInfo[2] === 'status'
        ) {
            $status = $input['status'] ?? null;

            if ($status === null || $status === '') {
                adminRespond(400, [
                    'detail' => 'Club status is required.',
                ]);
            }

            $pdo->prepare(
                'UPDATE clubs SET status = ? WHERE id = ?'
            )->execute([$status, $id]);

            adminRespond(200, [
                'message' => 'Club status updated',
            ]);
        } else {
            adminRespond(405, [
                'detail' => 'Unsupported club operation.',
            ]);
        }
    }

    // ============================================================
    // ADMIN MANAGEMENT
    // ============================================================
    elseif ($action === 'admins') {
        if ($method === 'GET') {
            $rows = $pdo->query(
                'SELECT
                    a.id,
                    a.name,
                    a.email,
                    a.role,
                    a.position,
                    a.campus,
                    a.permissions,
                    u.phone,
                    u.nrc,
                    u.gender,
                    u.country,
                    u.school,
                    u.program,
                    u.profile_picture
                 FROM admins a
                 LEFT JOIN users u
                   ON LOWER(u.email) = LOWER(a.email)
                 ORDER BY a.name'
            )->fetchAll(PDO::FETCH_ASSOC);

            adminRespond(200, $rows);
        } elseif ($method === 'POST') {
            $name = trim((string)($input['name'] ?? ''));
            $email = trim((string)($input['email'] ?? ''));
            $role = trim((string)($input['role'] ?? ''));
            $position = isset($input['position'])
                ? trim((string)$input['position'])
                : null;
            $campus = isset($input['campus'])
                ? trim((string)$input['campus'])
                : null;
            $password = (string)($input['password'] ?? '');
            $nrc = trim((string)($input['nrc'] ?? ''));

            if (
                $name === '' ||
                $email === '' ||
                $role === '' ||
                $password === '' ||
                $nrc === ''
            ) {
                adminRespond(422, [
                    'detail' =>
                    'Name, email, NRC / ID Number, role and password are required.',
                ]);
            }

            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                adminRespond(422, [
                    'detail' => 'A valid official email address is required.',
                ]);
            }

            $companionProfile = [];
            foreach (
                [
                    'phone',
                    'nrc',
                    'gender',
                    'country',
                    'school',
                    'program',
                    'profile_picture',
                ] as $profileKey
            ) {
                if (array_key_exists($profileKey, $input)) {
                    $companionProfile[$profileKey] = $input[$profileKey];
                }
            }

            $safePassword = substr($password, 0, 72);
            $hash = password_hash($safePassword, PASSWORD_BCRYPT);
            $permissions = adminNormalizePermissions(
                $input['permissions'] ?? null
            );

            $pdo->beginTransaction();

            try {
                $stmt = $pdo->prepare(
                    'INSERT INTO admins (
                        name,
                        email,
                        role,
                        position,
                        campus,
                        password,
                        permissions
                     )
                     VALUES (?, ?, ?, ?, ?, ?, ?)
                     RETURNING id'
                );

                $stmt->execute([
                    $name,
                    $email,
                    $role,
                    $position !== '' ? $position : null,
                    $campus !== '' ? $campus : null,
                    $hash,
                    $permissions,
                ]);

                $adminId = (int)$stmt->fetchColumn();
                $createdAdmin = adminFetchById($pdo, $adminId);

                if (!$createdAdmin) {
                    throw new RuntimeException(
                        'Administrator was inserted but could not be reloaded.'
                    );
                }

                // Create/synchronize the users row from the SAME request so NRC,
                // phone and other companion fields are not discarded.
                $userId = adminEnsureCompanionUser(
                    $pdo,
                    $createdAdmin,
                    $companionProfile
                );

                $pdo->commit();

                adminRespond(201, [
                    'status' => 'success',
                    'message' => 'Admin created successfully',
                    'id' => $adminId,
                    'user_id' => $userId,
                ]);
            } catch (Throwable $createError) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                throw $createError;
            }
        } elseif (
            $method === 'PUT' &&
            $id !== null &&
            ctype_digit((string)$id)
        ) {
            if (empty($input)) {
                adminRespond(400, [
                    'detail' =>
                    'Supply administrator fields to update.',
                ]);
            }

            $adminAllowed = [
                'name',
                'email',
                'role',
                'position',
                'campus',
                'password',
                'permissions',
            ];
            $profileAllowed = [
                'phone',
                'nrc',
                'gender',
                'country',
                'school',
                'program',
                'profile_picture',
            ];

            $fields = [];
            $params = [];
            $companionProfile = [];

            foreach ($input as $key => $value) {
                // full_name is a harmless Flutter alias; admins uses name.
                if ($key === 'full_name') {
                    continue;
                }

                if (in_array($key, $profileAllowed, true)) {
                    if ($value !== null && !is_string($value) && !is_numeric($value)) {
                        adminRespond(422, [
                            'detail' =>
                            'Invalid administrator profile field: ' . $key,
                        ]);
                    }
                    $companionProfile[$key] = $value;
                    continue;
                }

                if (!in_array($key, $adminAllowed, true)) {
                    adminRespond(400, [
                        'detail' =>
                        'Unsupported administrator field: ' . $key,
                    ]);
                }

                if ($key === 'permissions') {
                    $value = adminNormalizePermissions($value);
                } elseif ($key === 'password') {
                    if ($value === null || $value === '') {
                        continue;
                    }

                    if (!is_string($value)) {
                        adminRespond(400, [
                            'detail' => 'Password must be text.',
                        ]);
                    }

                    $value = password_hash(
                        substr($value, 0, 72),
                        PASSWORD_BCRYPT
                    );
                } elseif ($value !== null && !is_string($value)) {
                    adminRespond(400, [
                        'detail' =>
                        'Administrator fields must be text or null.',
                    ]);
                }

                $fields[] = "$key = ?";
                $params[] = $value;
            }

            if (empty($fields) && empty($companionProfile)) {
                adminRespond(400, [
                    'detail' => 'No editable values supplied.',
                ]);
            }

            $previousAdmin = adminFetchById($pdo, (int)$id);
            if (!$previousAdmin) {
                adminRespond(404, [
                    'detail' => 'Administrator not found.',
                ]);
            }

            $pdo->beginTransaction();

            try {
                if (!empty($fields)) {
                    $params[] = (int)$id;

                    $stmt = $pdo->prepare(
                        'UPDATE admins
                         SET ' . implode(', ', $fields) . '
                         WHERE id = ?
                         RETURNING id'
                    );
                    $stmt->execute($params);

                    if ($stmt->fetchColumn() === false) {
                        $pdo->rollBack();

                        adminRespond(404, [
                            'detail' => 'Administrator not found.',
                        ]);
                    }
                }

                $updatedAdmin = adminFetchById($pdo, (int)$id);

                if (!$updatedAdmin) {
                    throw new RuntimeException(
                        'Updated administrator could not be reloaded.'
                    );
                }

                $userId = adminEnsureCompanionUser(
                    $pdo,
                    $updatedAdmin,
                    $companionProfile,
                    (string)($previousAdmin['email'] ?? '')
                );

                $pdo->commit();

                adminRespond(200, [
                    'status' => 'success',
                    'message' =>
                    'Administrator updated successfully',
                    'user_id' => $userId,
                ]);
            } catch (Throwable $updateError) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                throw $updateError;
            }
        } elseif ($method === 'DELETE' && $id !== null) {
            $stmt = $pdo->prepare(
                'DELETE FROM admins
                 WHERE id = ?
                 RETURNING id'
            );
            $stmt->execute([$id]);

            if ($stmt->fetchColumn() === false) {
                adminRespond(404, [
                    'detail' => 'Administrator not found.',
                ]);
            }

            /*
             * We intentionally do not delete the companion users row.
             * Campus News/comments may already reference it.
             */
            adminRespond(200, [
                'status' => 'success',
                'message' => 'Administrator deleted successfully',
            ]);
        } else {
            adminRespond(405, [
                'detail' =>
                'Unsupported administrator operation or missing numeric ID.',
            ]);
        }
    } else {
        adminRespond(404, [
            'detail' => 'Endpoint not found',
        ]);
    }
} catch (InvalidArgumentException $e) {
    adminRespond(422, [
        'detail' => $e->getMessage(),
    ]);
} catch (PDOException $e) {
    adminRespond(500, [
        'detail' => 'Database error: ' . $e->getMessage(),
    ]);
} catch (Throwable $e) {
    adminRespond(500, [
        'detail' => 'Server error: ' . $e->getMessage(),
    ]);
}
