<?php
declare(strict_types=1);
namespace App\Controllers;

use App\Core\Controller;
use App\Repositories\ReturnRepository;
use App\Services\AuditService;

final class ReturnController extends Controller {
    public function index(): void {
        require_role(['admin','reception','reports']);
        $q = trim((string)($_GET['q'] ?? ''));
        $rows = (new ReturnRepository())->pendingInvoices($q);
        $this->view('returns/index', compact('rows', 'q'));
    }

    public function show(): void {
        require_role(['admin','reception','reports']);
        $id = (int)($_GET['id'] ?? 0);
        $repo = new ReturnRepository();
        $invoice = $repo->invoiceWithLines($id);
        if (!$invoice) {
            http_response_code(404);
            $this->view('errors/404');
            return;
        }
        $items = $repo->lines($id);
        $this->view('returns/show', compact('invoice', 'items'));
    }

    public function process(): void {
        require_role(['admin','reception','reports']);
        verify_csrf();

        $invoiceId = (int)($_POST['id'] ?? 0);
        $ids = array_map('intval', (array)($_POST['return_item_id'] ?? []));

        $payment = [
            'amount' => (float)($_POST['settlement_amount'] ?? 0),
            'payment_method' => trim((string)($_POST['payment_method'] ?? 'cash')),
            'transfer_reference' => trim((string)($_POST['transfer_reference'] ?? '')),
            'notes' => trim((string)($_POST['payment_notes'] ?? '')),
        ];

        if (!$ids && $payment['amount'] <= 0) {
            flash('error', 'اختر قطعة واحدة على الأقل للإرجاع أو أدخل مبلغ تصفية للفاتورة');
            redirect(base_url('?page=return_show&id=' . $invoiceId));
        }

        (new ReturnRepository())->processReturn(
            $invoiceId,
            $ids,
            (array)($_POST['return_condition'] ?? []),
            (int)($_SESSION['uid'] ?? 1),
            $payment
        );

        (new AuditService())->log('returns', 'process', $invoiceId, [
            'items' => $ids,
            'settlement_amount' => $payment['amount'],
            'payment_method' => $payment['payment_method'],
        ]);

        flash('success', 'تم تحديث الإرجاع وتصفية المبلغ بنجاح');
        redirect(base_url('?page=return_show&id=' . $invoiceId));
    }
}
