<?php
declare(strict_types=1);

namespace App\Modules\Receipts\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Receipts\Models\Receipt;
use App\Modules\Payments\Services\PaymentService;
use App\Modules\Payments\Models\Payment;

class ReceiptController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'search'    => trim((string) $request->get('q', '')),
            'is_voided' => '0',
            'date_from' => $request->get('date_from', ''),
            'date_to'   => $request->get('date_to', ''),
        ];
        $page = max(1, (int) $request->get('page', 1));
        $result = Receipt::search($filters, 25, $page);

        return $this->view('Receipts.Views.index', [
            'rows'       => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
            'title'      => 'الإيصالات',
        ]);
    }

    public function voided(Request $request): Response
    {
        $filters = [
            'search'    => trim((string) $request->get('q', '')),
            'is_voided' => '1',
            'date_from' => $request->get('date_from', ''),
            'date_to'   => $request->get('date_to', ''),
        ];
        $page = max(1, (int) $request->get('page', 1));
        $result = Receipt::search($filters, 25, $page);

        return $this->view('Receipts.Views.index', [
            'rows'       => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
            'title'      => 'الإيصالات الملغاة',
            'showVoided' => true,
        ]);
    }

    public function printReceipt(Request $request, string $id): Response
    {
        $receipt = Receipt::findWithDetails((int) $id);
        if (!$receipt) return $this->redirect('/receipts')->withError('الإيصال غير موجود');

        // Increment print count
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();
        $db->query("UPDATE receipts SET print_count = print_count + 1, last_printed_at = ?, last_printed_by = ? WHERE id = ?", [
            date('Y-m-d H:i:s'), $employee ? (int) $employee->id : null, (int) $id
        ]);

        return $this->view('Receipts.Views.print', ['receipt' => $receipt]);
    }

    public function voidReceipt(Request $request, string $id): Response
    {
        $receipt = Receipt::find((int) $id);
        if (!$receipt) return $this->redirect('/receipts')->withError('الإيصال غير موجود');

        $reason = trim((string) $request->post('void_reason', ''));
        if ($reason === '') return $this->redirect('/receipts')->withError('يجب إدخال سبب الإلغاء');

        if ($receipt['payment_id']) {
            $result = PaymentService::voidPayment((int) $receipt['payment_id'], $reason);
            if (!$result['success']) {
                return $this->redirect('/receipts')->withError($result['error']);
            }
        } else {
            $employee = App::getInstance()->currentEmployee();
            $db = App::getInstance()->db();
            $db->update('receipts', [
                'is_voided'  => 1,
                'voided_at'  => date('Y-m-d H:i:s'),
                'voided_by'  => $employee ? (int) $employee->id : null,
                'void_reason'=> $reason,
            ], '`id` = ?', [(int) $id]);
        }

        return $this->redirect('/receipts')->withSuccess('تم إلغاء الإيصال بنجاح');
    }
}