<?php
// api/request_workflow.php
// Rockview University campus-aware request routing.
// Controlled workflow: Staff -> Registrar -> DVC1 -> Accountant or direct CFO -> CFO -> CEO (optional).
// CFO may return to Accountant for correction/review or escalate to CEO.

require_once __DIR__ . '/request_workflow_common.php';

function rvu_req_finalize(PDO $pdo, array $user, array $request, string $status, string $remarks): void {
    $actor = rvu_req_official_profile($pdo, $user);
    $id = (int)$request['id'];

    $update = $pdo->prepare("UPDATE workflow_requests SET status = ?, updated_at = CURRENT_TIMESTAMP, finalized_at = CURRENT_TIMESTAMP WHERE id = ?");
    $update->execute([$status, $id]);

    $route = $pdo->prepare("INSERT INTO workflow_request_routes (
        request_id, action, actor_user_id, actor_name, actor_position, actor_campus,
        from_position, from_campus, remarks
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $route->execute([
        $id, $status, (int)$user['id'], $user['full_name'], $actor['position'], $actor['campus'],
        $request['recipient_position'], $request['target_campus'], $remarks,
    ]);

    rvu_req_mark_action_notifications_read($pdo, $id);
    $title = $status === 'approved' ? 'Request approved' : ($status === 'cancelled' ? 'Request cancelled' : 'Request declined');
    rvu_req_notify(
        $pdo,
        $id,
        [(int)$request['requester_user_id']],
        $status,
        $title,
        '"' . $request['reference'] . '" was ' . $status . ' by ' . ($actor['position'] ?: 'an administrator') . ' at ' . ($actor['campus'] ?: $request['target_campus']) . '.'
    );
}

try {
    rvu_req_ensure_tables($pdo);
    $user = rvu_req_user($pdo);
    $profile = rvu_req_official_profile($pdo, $user);
    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

    if ($method === 'GET') {
        $action = strtolower(trim((string)($_GET['action'] ?? '')));
        if ($action === 'directory') {
            rvu_req_json(rvu_req_directory($pdo, $user, $_GET['campus'] ?? null));
        }

        if ($action === 'summary') {
            $stmt = $pdo->query("SELECT * FROM workflow_requests ORDER BY created_at DESC LIMIT 1000");
            $actionCount = 0;
            $trackingCount = 0;
            $processedCount = 0;
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                if (($row['status'] ?? '') === 'pending') {
                    if ((int)$row['requester_user_id'] === (int)$user['id']) $trackingCount++;
                    if (rvu_req_can_process($pdo, $user, $row)) $actionCount++;
                } elseif (rvu_req_can_view($pdo, $user, $row)) {
                    $processedCount++;
                }
            }
            $n = $pdo->prepare("SELECT COUNT(*) FROM workflow_request_notifications WHERE recipient_user_id = ? AND is_read = FALSE");
            $n->execute([(int)$user['id']]);
            rvu_req_json([
                'action_required_count' => $actionCount,
                'tracking_count' => $trackingCount,
                'processed_count' => $processedCount,
                'unread_notifications' => (int)$n->fetchColumn(),
                'is_admin' => (bool)$profile['is_admin'],
                'current_user' => $profile,
                'workflow_label' => 'Staff -> Registrar -> DVC1 -> Accountant/CFO -> CFO -> CEO (optional)',
            ]);
        }

        $id = isset($_GET['id']) && ctype_digit((string)$_GET['id']) ? (int)$_GET['id'] : null;
        if ($id !== null) {
            $stmt = $pdo->prepare('SELECT * FROM workflow_requests WHERE id = ? LIMIT 1');
            $stmt->execute([$id]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$row) rvu_req_json(['detail' => 'Request not found.'], 404);
            if (!rvu_req_can_view($pdo, $user, $row)) rvu_req_json(['detail' => 'You do not have access to this request.'], 403);
            rvu_req_json(rvu_req_public_row($pdo, $row, $user));
        }

        $scope = strtolower(trim((string)($_GET['scope'] ?? 'pending')));
        if (!in_array($scope, ['pending', 'processed', 'all'], true)) $scope = 'pending';
        $search = mb_strtolower(trim((string)($_GET['search'] ?? '')), 'UTF-8');

        $stmt = $pdo->query("SELECT * FROM workflow_requests ORDER BY updated_at DESC, id DESC LIMIT 1000");
        $rows = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $status = strtolower((string)($row['status'] ?? ''));
            if ($scope === 'pending' && $status !== 'pending') continue;
            if ($scope === 'processed' && $status === 'pending') continue;
            if (!rvu_req_can_view($pdo, $user, $row)) continue;
            if ($search !== '') {
                $haystack = mb_strtolower(implode(' ', [
                    $row['reference'] ?? '', $row['body'] ?? '', $row['requester_name'] ?? '',
                    $row['recipient_position'] ?? '', $row['target_campus'] ?? '', $row['category'] ?? '',
                ]), 'UTF-8');
                if (mb_strpos($haystack, $search) === false) continue;
            }
            $rows[] = rvu_req_public_row($pdo, $row, $user);
        }
        rvu_req_json(['data' => $rows, 'count' => count($rows), 'current_user' => $profile]);
    }

    if ($method === 'POST') {
        $input = rvu_req_input();
        $targetCampus = rvu_req_clean($profile['campus'] ?? '', 180);
        if ($targetCampus === '' || strtolower($targetCampus) === 'null') {
            rvu_req_json(['detail' => 'Your signed-in account must have a campus before you can make an official request.'], 422);
        }

        // The first routing destination is never selected by the client.
        // Every new request goes to the Registrar of the requester's campus.
        $registrar = rvu_req_position_for_stage($pdo, 'registrar');
        if (!$registrar) {
            rvu_req_json(['detail' => 'The Registrar position is not configured in the positions table. Add REGISTRAR or THE REGISTRAR first.'], 422);
        }
        $positionId = (int)$registrar['id'];
        $position = rvu_req_clean($registrar['title'] ?? '', 180);
        $recipients = rvu_req_recipient_users($pdo, $position, $targetCampus, $positionId);
        if (!$recipients) {
            rvu_req_json(['detail' => 'No administrator is assigned as Registrar at ' . $targetCampus . '. Configure the campus Registrar in Routing Directory first.'], 422);
        }

        $reference = rvu_req_clean($input['reference'] ?? '', 240);
        $body = trim((string)($input['body'] ?? ''));
        if ($reference === '' || $body === '') {
            rvu_req_json(['detail' => 'RE/subject and the body of the request are required.'], 422);
        }

        $priority = strtolower(rvu_req_clean($input['priority'] ?? 'normal', 20));
        if (!in_array($priority, ['normal', 'important', 'urgent'], true)) $priority = 'normal';
        $category = rvu_req_clean($input['category'] ?? 'General', 80);
        if ($category === '') $category = 'General';
        $amount = isset($input['amount']) && $input['amount'] !== '' ? (float)$input['amount'] : null;
        $tableData = rvu_req_normalize_table_payload($input['table_data'] ?? null);
        $tableJson = $tableData === null ? null : json_encode($tableData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        $requesterPosition = rvu_req_clean($profile['position'] ?? '', 180);
        $hint = rvu_req_clean($input['sender_position_hint'] ?? '', 180);
        if ($hint !== '' && in_array(rvu_req_norm($requesterPosition), ['STAFF', 'ADMIN', 'ADMINISTRATOR'], true)) {
            $requesterPosition = $hint;
        }

        $pdo->beginTransaction();
        $sql = "INSERT INTO workflow_requests (
                    requester_user_id, requester_name, requester_email, requester_position, requester_campus,
                    recipient_position_id, recipient_position, target_campus, current_stage,
                    reference, body, category, priority, amount, table_data
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'registrar', ?, ?, ?, ?, ?, ?::jsonb) RETURNING id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            (int)$user['id'], $user['full_name'], $user['email'], $requesterPosition, $targetCampus,
            $positionId, $position, $targetCampus,
            $reference, $body, $category, $priority, $amount, $tableJson,
        ]);
        $requestId = (int)$stmt->fetchColumn();

        $route = $pdo->prepare("INSERT INTO workflow_request_routes (
            request_id, action, actor_user_id, actor_name, actor_position, actor_campus,
            to_position_id, to_position, to_campus, remarks
        ) VALUES (?, 'submitted', ?, ?, ?, ?, ?, ?, ?, ?)");
        $route->execute([
            $requestId, (int)$user['id'], $user['full_name'], $requesterPosition, $targetCampus,
            $positionId, $position, $targetCampus, 'Official request submitted to the campus Registrar.',
        ]);

        $recipientIds = array_map(fn($r) => (int)$r['id'], $recipients);
        rvu_req_notify(
            $pdo,
            $requestId,
            $recipientIds,
            'action_required',
            'New request for Registrar action',
            $user['full_name'] . ' submitted "' . $reference . '" at ' . $targetCampus . '. Registrar action is required.'
        );
        $pdo->commit();

        rvu_req_json([
            'id' => $requestId,
            'message' => 'Request dispatched to the Registrar successfully.',
            'current_stage' => 'registrar',
            'recipient_position' => $position,
            'target_campus' => $targetCampus,
            'notified_users' => count($recipientIds),
        ], 201);
    }

    if ($method === 'PUT') {
        $id = isset($_GET['id']) && ctype_digit((string)$_GET['id']) ? (int)$_GET['id'] : 0;
        if ($id <= 0) rvu_req_json(['detail' => 'A valid request ID is required.'], 400);
        $input = rvu_req_input();
        $action = strtolower(rvu_req_clean($input['action'] ?? '', 40));
        $routeActions = ['route', 'route_dvc1', 'route_accountant', 'route_cfo', 'route_ceo'];
        if (!in_array($action, array_merge($routeActions, ['approve', 'cancel', 'decline']), true)) {
            rvu_req_json(['detail' => 'Action must be a permitted route, approve, or cancel operation.'], 422);
        }

        $pdo->beginTransaction();
        $stmt = $pdo->prepare('SELECT * FROM workflow_requests WHERE id = ? FOR UPDATE');
        $stmt->execute([$id]);
        $request = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$request) { $pdo->rollBack(); rvu_req_json(['detail' => 'Request not found.'], 404); }
        if (($request['status'] ?? '') !== 'pending') { $pdo->rollBack(); rvu_req_json(['detail' => 'This request has already been finalized.'], 409); }

        if (!rvu_req_is_admin_account($pdo, $user)) {
            $pdo->rollBack();
            rvu_req_json(['detail' => 'Only administrator accounts may approve, escalate, or cancel official requests.'], 403);
        }
        if (!rvu_req_can_process($pdo, $user, $request)) {
            $pdo->rollBack();
            rvu_req_json(['detail' => 'Your administrator position and campus do not match the current action point for this request.'], 403);
        }

        $remarks = rvu_req_clean($input['remarks'] ?? '', 3000);
        $actor = rvu_req_official_profile($pdo, $user);
        $fromPosition = $request['recipient_position'];
        $fromCampus = $request['target_campus'];
        $currentStage = rvu_req_request_stage($request);

        if (in_array($action, $routeActions, true)) {
            $allowedStages = rvu_req_next_stages($currentStage);
            if (!$allowedStages) {
                $pdo->rollBack();
                rvu_req_json(['detail' => 'This office has no configured next routing step.'], 422);
            }

            $explicitStage = '';
            if (strpos($action, 'route_') === 0) {
                $explicitStage = substr($action, strlen('route_'));
            }

            if ($explicitStage !== '') {
                if (!in_array($explicitStage, $allowedStages, true)) {
                    $pdo->rollBack();
                    rvu_req_json([
                        'detail' => rvu_req_stage_label($explicitStage) . ' is not a permitted destination from ' . rvu_req_stage_label($currentStage) . '.'
                    ], 422);
                }
                $nextStage = $explicitStage;
            } else {
                if (count($allowedStages) > 1) {
                    $pdo->rollBack();
                    rvu_req_json([
                        'detail' => 'Choose the destination office before routing this request.'
                    ], 422);
                }
                $nextStage = $allowedStages[0];
            }

            $nextPosition = rvu_req_position_for_stage($pdo, $nextStage);
            if (!$nextPosition) {
                $pdo->rollBack();
                rvu_req_json(['detail' => rvu_req_stage_label($nextStage) . ' is missing from the positions table.'], 422);
            }

            $positionId = (int)$nextPosition['id'];
            $position = rvu_req_clean($nextPosition['title'] ?? '', 180);

            // Registrar belongs to the request origin campus. Every subsequent
            // workflow office (DVC1, Accountant, CFO and CEO) is resolved at HQ.
            $originCampus = rvu_req_request_origin_campus($request);
            $targetCampus = rvu_req_routing_campus($pdo, $nextStage, $originCampus);

            $recipients = rvu_req_recipient_users($pdo, $position, $targetCampus, $positionId);
            if (!$recipients) {
                $pdo->rollBack();
                rvu_req_json([
                    'detail' => 'No administrator is assigned as ' . $position . ' at ' . $targetCampus . '. Configure that office holder before routing.'
                ], 422);
            }

            $update = $pdo->prepare("UPDATE workflow_requests
                SET recipient_position_id = ?,
                    recipient_position = ?,
                    target_campus = ?,
                    current_stage = ?,
                    updated_at = CURRENT_TIMESTAMP
                WHERE id = ?");
            $update->execute([$positionId, $position, $targetCampus, $nextStage, $id]);

            $route = $pdo->prepare("INSERT INTO workflow_request_routes (
                request_id, action, actor_user_id, actor_name, actor_position, actor_campus,
                from_position, from_campus, to_position_id, to_position, to_campus, remarks
            ) VALUES (?, 'routed', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $route->execute([
                $id, (int)$user['id'], $user['full_name'], $actor['position'], $actor['campus'],
                $fromPosition, $fromCampus, $positionId, $position, $targetCampus, $remarks,
            ]);

            rvu_req_mark_action_notifications_read($pdo, $id);
            $recipientIds = array_map(fn($r) => (int)$r['id'], $recipients);
            rvu_req_notify(
                $pdo,
                $id,
                $recipientIds,
                'action_required',
                'Request requires your action',
                '"' . $request['reference'] . '" was routed from ' . $fromPosition . ' to ' . $position . ' at ' . $targetCampus . '.'
            );
            rvu_req_notify(
                $pdo,
                $id,
                [(int)$request['requester_user_id']],
                'routed',
                'Your request was routed',
                '"' . $request['reference'] . '" was routed to ' . $position . ' at ' . $targetCampus . '.'
            );
            $pdo->commit();
            rvu_req_json([
                'message' => 'Request routed to ' . $position . ' successfully.',
                'current_stage' => $nextStage,
                'recipient_position' => $position,
                'target_campus' => $targetCampus,
                'notified_users' => count($recipientIds),
            ]);
        }

        if ($action === 'approve') {
            rvu_req_finalize($pdo, $user, $request, 'approved', $remarks === '' ? 'Approved.' : $remarks);
            $pdo->commit();
            rvu_req_json(['message' => 'Request approved successfully.', 'status' => 'approved']);
        }

        if ($action === 'cancel') {
            rvu_req_finalize($pdo, $user, $request, 'cancelled', $remarks === '' ? 'Cancelled by the responsible administrator.' : $remarks);
            $pdo->commit();
            rvu_req_json(['message' => 'Request cancelled successfully.', 'status' => 'cancelled']);
        }

        // Legacy compatibility only. New Flutter UI uses CANCEL, not DECLINE.
        rvu_req_finalize($pdo, $user, $request, 'declined', $remarks === '' ? 'Declined by the responsible administrator.' : $remarks);
        $pdo->commit();
        rvu_req_json(['message' => 'Request declined successfully.', 'status' => 'declined']);
    }

    if ($method === 'DELETE') {
        // Compatibility route: DELETE now follows the same administrator-only
        // rules as the CANCEL action. Staff/requesters cannot cancel their own request.
        $id = isset($_GET['id']) && ctype_digit((string)$_GET['id']) ? (int)$_GET['id'] : 0;
        if ($id <= 0) rvu_req_json(['detail' => 'A valid request ID is required.'], 400);
        $pdo->beginTransaction();
        $stmt = $pdo->prepare('SELECT * FROM workflow_requests WHERE id = ? FOR UPDATE');
        $stmt->execute([$id]);
        $request = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$request) { $pdo->rollBack(); rvu_req_json(['detail' => 'Request not found.'], 404); }
        if (($request['status'] ?? '') !== 'pending') { $pdo->rollBack(); rvu_req_json(['detail' => 'Only pending requests can be cancelled.'], 409); }
        if (!rvu_req_is_admin_account($pdo, $user) || !rvu_req_can_process($pdo, $user, $request)) {
            $pdo->rollBack();
            rvu_req_json(['detail' => 'Only the administrator currently responsible for this request may cancel it.'], 403);
        }
        rvu_req_finalize($pdo, $user, $request, 'cancelled', 'Cancelled by the responsible administrator.');
        $pdo->commit();
        rvu_req_json(['message' => 'Request cancelled successfully.']);
    }

    rvu_req_json(['detail' => 'Method not allowed.'], 405);
} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) $pdo->rollBack();
    error_log('Request workflow error: ' . $e->getMessage());
    rvu_req_json(['detail' => 'The request workflow service encountered an unexpected server error.'], 500);
}
