<?php

namespace App\Services\Expenses;

use App\Models\Expense;

class ExpenseWriteService
{
    public function __construct(private ExpenseContextService $context) {}

    public function store(array $payload): Expense
    {
        $schoolYear = $payload['school_year'] ?? $this->context->getSchoolYear();
        $semester = $payload['semester'] ?? $this->context->getSemester();

        $data = [
            'category' => $payload['category'],
            'amount' => $payload['amount'],
            'receipt_path' => $payload['receipt_path'] ?? null,
            'description' => $payload['description'] ?? null,
            'retailor' => $payload['retailor'] ?? null,
            'date_of_purchase' => $payload['date_of_purchase'],
            'purchased_by' => $payload['purchased_by'],
            'added_by' => $payload['added_by'],
            'status' => $payload['status'],
            'status_reason' => $payload['status_reason'] ?? null,
            'approved_by' => $payload['approved_by'] ?? null,
            'school_year' => $schoolYear,
            'semester' => $semester,
        ];

        return Expense::query()->create($data);
    }

    public function update(Expense $expense, array $payload): Expense
    {
        $expense->fill($payload);
        $expense->save();
        return $expense;
    }
}
