<?php
/** Approval inbox — list pending for this approver, decide, disburse. */
require_once __DIR__ . '/_boot.php';

$action = fin_in('action', '');

switch ($action) {

    // Requests currently awaiting THIS user's role (admin sees all pending).
    case 'inbox': {
        $rows = [];
        $res = $conn->query("SELECT * FROM expense_requests WHERE status='pending' ORDER BY id DESC LIMIT 300");
        while ($res && $row = $res->fetch_assoc()) {
            if (finance_can_approve($conn, $row, $actor['role'])) {
                $step = finance_current_required_step($conn, $row);
                $row['step_label'] = $step['label'] ?? 'Pending';
                $rows[] = $row;
            }
        }
        // Approved-but-not-disbursed, for disbursers.
        $ready = [];
        if (in_array($actor['role'], ['admin', 'accountant'], true)) {
            $r2 = $conn->query("SELECT * FROM expense_requests WHERE status='approved' ORDER BY id DESC LIMIT 100");
            while ($r2 && $row = $r2->fetch_assoc()) $ready[] = $row;
        }
        fin_out(['success' => true, 'pending' => $rows, 'ready' => $ready]);
    }

    case 'decide': {
        $id      = (int) fin_in('id', 0);
        $decision = fin_in('decision', '');   // 'approved' | 'rejected'
        $comment  = trim((string) fin_in('comment', ''));
        $stmt = $conn->prepare("SELECT * FROM expense_requests WHERE id = ?");
        $stmt->bind_param('i', $id); $stmt->execute();
        $req = $stmt->get_result()->fetch_assoc(); $stmt->close();
        if (!$req) fin_out(['success' => false, 'message' => 'Request not found.']);

        $result = finance_process_decision($conn, $req, $decision, $comment, $actor);
        if ($result['ok'] && ($result['status'] ?? '') === 'pending') {
            finance_notify_next($conn, $id);
        }
        fin_out(['success' => $result['ok'], 'message' => $result['message'], 'status' => $result['status'] ?? null]);
    }

    case 'disburse': {
        if (!in_array($actor['role'], ['admin', 'accountant'], true)) {
            fin_out(['success' => false, 'message' => 'Only the Bursar/Accountant or Admin can disburse.']);
        }
        $id = (int) fin_in('id', 0);
        $stmt = $conn->prepare("SELECT * FROM expense_requests WHERE id = ?");
        $stmt->bind_param('i', $id); $stmt->execute();
        $req = $stmt->get_result()->fetch_assoc(); $stmt->close();
        if (!$req) fin_out(['success' => false, 'message' => 'Request not found.']);
        $result = finance_disburse($conn, $req);
        fin_out(['success' => $result['ok'], 'message' => $result['message']]);
    }

    default:
        fin_out(['success' => false, 'message' => 'Unknown action.']);
}

function finance_notify_next(mysqli $conn, int $rid): void
{
    if (!function_exists('sendSMS') || !function_exists('getSettingValue')) return;
    $stmt = $conn->prepare("SELECT * FROM expense_requests WHERE id = ?");
    $stmt->bind_param('i', $rid); $stmt->execute();
    $req = $stmt->get_result()->fetch_assoc(); $stmt->close();
    if (!$req) return;
    $step = finance_current_required_step($conn, $req);
    $phone = getSettingValue('school_phone');
    if (!$step || !$phone) return;
    $amt = function_exists('formatCurrency') ? formatCurrency((float) $req['amount']) : $req['amount'];
    @sendSMS($phone, "Request {$req['request_no']} ({$amt}) now awaits {$step['label']} approval.");
}
