<?php

namespace Modules\Procurement\Services;

use App\Models\ActivityLogModel;
use App\Models\PurchaseRequestLineModel;
use App\Models\PurchaseRequestModel;

class PurchaseRequestService
{
    protected PurchaseRequestModel $requests;
    protected PurchaseRequestLineModel $lines;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->requests = new PurchaseRequestModel();
        $this->lines    = new PurchaseRequestLineModel();
        $this->activity = new ActivityLogModel();
    }

    public function create(array $input, ?int $actingUserId): array
    {
        $data = $this->mapInput($input);
        $data['number']     = $this->requests->nextNumber();
        $data['status']     = in_array($input['status'] ?? 'draft', ['draft', 'pending_approval'], true)
            ? ($input['status'] ?? 'draft')
            : 'draft';
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

        if (! $this->requests->insert($data, true)) {
            return ['success' => false, 'errors' => $this->requests->errors()];
        }

        $id = (int) $this->requests->getInsertID();
        $result = $this->lines->replaceForPurchaseRequest($id, $input['lines'] ?? []);
        $tax = (float) ($input['tax_amount'] ?? 0);
        $this->requests->update($id, [
            'subtotal'   => $result['subtotal'],
            'tax_amount' => $tax,
            'total'      => round($result['subtotal'] + $tax, 2),
        ]);

        $this->activity->log('purchase_requests', 'created', $actingUserId, "Created purchase request #{$id} ({$data['number']})", (string) $id);

        return ['success' => true, 'id' => $id];
    }

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $request = $this->requests->find($id);
        if (! $request) {
            return ['success' => false, 'errors' => ['id' => 'Purchase request not found.']];
        }

        if (! in_array($request['status'], ['draft', 'rejected'], true)) {
            return ['success' => false, 'errors' => ['status' => 'Only draft or rejected purchase requests can be edited.']];
        }

        $data = $this->mapInput($input);
        $data['updated_by'] = $actingUserId;

        if (! $this->requests->update($id, $data)) {
            return ['success' => false, 'errors' => $this->requests->errors()];
        }

        $result = $this->lines->replaceForPurchaseRequest($id, $input['lines'] ?? []);
        $tax = (float) ($input['tax_amount'] ?? 0);
        $this->requests->update($id, [
            'subtotal'   => $result['subtotal'],
            'tax_amount' => $tax,
            'total'      => round($result['subtotal'] + $tax, 2),
            'updated_by' => $actingUserId,
        ]);

        $this->activity->log('purchase_requests', 'updated', $actingUserId, "Updated purchase request #{$id}", (string) $id);

        return ['success' => true];
    }

    public function submitForApproval(int $id, ?int $actingUserId): array
    {
        $request = $this->requests->find($id);
        if (! $request) {
            return ['success' => false, 'error' => 'Purchase request not found.'];
        }
        if (! in_array($request['status'], ['draft', 'rejected'], true)) {
            return ['success' => false, 'error' => 'Only draft or rejected purchase requests can be submitted.'];
        }

        $this->requests->update($id, [
            'status'           => 'pending_approval',
            'rejection_reason' => null,
            'updated_by'       => $actingUserId,
        ]);
        $this->activity->log('purchase_requests', 'submitted', $actingUserId, "Submitted purchase request #{$id} for approval", (string) $id);

        return ['success' => true];
    }

    public function approve(int $id, ?int $actingUserId): array
    {
        $request = $this->requests->find($id);
        if (! $request) {
            return ['success' => false, 'error' => 'Purchase request not found.'];
        }
        if ($request['status'] !== 'pending_approval') {
            return ['success' => false, 'error' => 'Purchase request is not pending approval.'];
        }

        $this->requests->update($id, [
            'status'           => 'approved',
            'rejection_reason' => null,
            'approved_by'      => $actingUserId,
            'approved_at'      => date('Y-m-d H:i:s'),
            'updated_by'       => $actingUserId,
        ]);
        $this->activity->log('purchase_requests', 'approved', $actingUserId, "Approved purchase request #{$id}", (string) $id);

        return ['success' => true];
    }

    public function reject(int $id, string $reason, ?int $actingUserId): array
    {
        $request = $this->requests->find($id);
        if (! $request) {
            return ['success' => false, 'error' => 'Purchase request not found.'];
        }
        if ($request['status'] !== 'pending_approval') {
            return ['success' => false, 'error' => 'Purchase request is not pending approval.'];
        }

        $this->requests->update($id, [
            'status'           => 'rejected',
            'rejection_reason' => trim($reason) ?: 'Rejected',
            'updated_by'       => $actingUserId,
        ]);
        $this->activity->log('purchase_requests', 'rejected', $actingUserId, "Rejected purchase request #{$id}", (string) $id);

        return ['success' => true];
    }

    public function cancel(int $id, ?int $actingUserId): array
    {
        $request = $this->requests->find($id);
        if (! $request) {
            return ['success' => false, 'error' => 'Purchase request not found.'];
        }
        if (in_array($request['status'], ['converted', 'cancelled'], true)) {
            return ['success' => false, 'error' => 'Purchase request cannot be cancelled.'];
        }

        $this->requests->update($id, ['status' => 'cancelled', 'updated_by' => $actingUserId]);
        $this->activity->log('purchase_requests', 'cancelled', $actingUserId, "Cancelled purchase request #{$id}", (string) $id);

        return ['success' => true];
    }

    public function delete(int $id, ?int $actingUserId): array
    {
        $request = $this->requests->find($id);
        if (! $request) {
            return ['success' => false, 'error' => 'Purchase request not found.'];
        }
        if (! in_array($request['status'], ['draft', 'cancelled', 'rejected'], true)) {
            return ['success' => false, 'error' => 'Only draft, rejected, or cancelled purchase requests can be deleted.'];
        }

        $this->lines->where('purchase_request_id', $id)->delete();
        $this->requests->delete($id);
        $this->activity->log('purchase_requests', 'deleted', $actingUserId, "Deleted purchase request #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'request_date' => $input['request_date'] ?? date('Y-m-d'),
            'needed_by'    => ! empty($input['needed_by']) ? $input['needed_by'] : null,
            'department'   => trim((string) ($input['department'] ?? '')) ?: null,
            'notes'        => $input['notes'] ?: null,
        ];
    }
}
