<?php
/** Receipt attachments — upload / list / delete, linked to a request or expense. */
require_once __DIR__ . '/_boot.php';

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

switch ($action) {

    case 'upload': {
        $request_id = (int) fin_in('request_id', 0) ?: null;
        $expense_id = (int) fin_in('expense_id', 0) ?: null;
        if (!$request_id && !$expense_id) {
            fin_out(['success' => false, 'message' => 'A request or expense must be specified.']);
        }
        if (empty($_FILES['receipt']) || ($_FILES['receipt']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
            fin_out(['success' => false, 'message' => 'No file received.']);
        }
        $err  = null;
        $path = finance_save_receipt($_FILES['receipt'], $err);
        if (!$path) fin_out(['success' => false, 'message' => $err ?: 'Upload failed.']);

        $orig = mb_substr((string) $_FILES['receipt']['name'], 0, 200);
        $mime = (string) (new finfo(FILEINFO_MIME_TYPE))->file($_FILES['receipt']['tmp_name']);
        $size = (int) $_FILES['receipt']['size'];
        $stmt = $conn->prepare("INSERT INTO expense_attachments
            (request_id, expense_id, file_path, original_name, mime, size, uploaded_by, uploaded_by_name)
            VALUES (?,?,?,?,?,?,?,?)");
        $stmt->bind_param('iisssiis', $request_id, $expense_id, $path, $orig, $mime, $size, $actor['id'], $actor['name']);
        $stmt->execute();
        $newId = $stmt->insert_id;
        $stmt->close();
        fin_out(['success' => true, 'id' => $newId, 'file_path' => $path, 'mime' => $mime, 'original_name' => $orig, 'message' => 'Receipt attached.']);
    }

    case 'list': {
        $request_id = (int) fin_in('request_id', 0) ?: null;
        $expense_id = (int) fin_in('expense_id', 0) ?: null;
        if ($request_id) {
            $stmt = $conn->prepare("SELECT id, file_path, original_name, mime, uploaded_by_name, created_at FROM expense_attachments WHERE request_id = ? ORDER BY id");
            $stmt->bind_param('i', $request_id);
        } else {
            $stmt = $conn->prepare("SELECT id, file_path, original_name, mime, uploaded_by_name, created_at FROM expense_attachments WHERE expense_id = ? ORDER BY id");
            $stmt->bind_param('i', $expense_id);
        }
        $stmt->execute();
        $res = $stmt->get_result();
        $rows = [];
        while ($row = $res->fetch_assoc()) $rows[] = $row;
        $stmt->close();
        fin_out(['success' => true, 'data' => $rows]);
    }

    case 'delete': {
        if (!in_array($actor['role'], ['admin', 'accountant', 'headteacher'], true)) {
            fin_out(['success' => false, 'message' => 'Not permitted.']);
        }
        $id = (int) fin_in('id', 0);
        $stmt = $conn->prepare("SELECT file_path FROM expense_attachments WHERE id = ?");
        $stmt->bind_param('i', $id); $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc(); $stmt->close();
        if ($row) {
            $abs = __DIR__ . '/../../' . $row['file_path'];
            if (is_file($abs)) @unlink($abs);
            $conn->query("DELETE FROM expense_attachments WHERE id = " . $id);
        }
        fin_out(['success' => true, 'message' => 'Receipt removed.']);
    }

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