<?php

declare(strict_types=1);

namespace backend\controllers;

use common\forms\InvoiceForm;
use common\models\Customer;
use common\models\Invoice;
use common\models\Payment;
use common\services\InvoiceService;
use common\services\PdfService;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\Response;

/**
 * InvoiceController — create, view, list invoices and record payments.
 */
class InvoiceController extends Controller
{
    private InvoiceService $service;

    public function init(): void
    {
        parent::init();
        $this->service = new InvoiceService();
    }

    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [['allow' => true, 'roles' => ['@']]],
            ],
            'verbs' => [
                'class'   => VerbFilter::class,
                'actions' => [
                    'pay'    => ['POST'],
                    'cancel' => ['POST'],
                ],
            ],
        ];
    }

    public function actionIndex(): string
    {
        $query = Invoice::find()
            ->with(['customer'])
            ->orderBy(['created_at' => SORT_DESC]);

        $status = \Yii::$app->request->get('status');
        if ($status) {
            $query->andWhere(['status' => $status]);
        }

        $dataProvider = new ActiveDataProvider([
            'query'      => $query,
            'pagination' => ['pageSize' => 20],
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'filterStatus' => $status,
        ]);
    }

    public function actionView(int $id): string
    {
        $model = $this->findModel($id);
        $model->populateRelation('items', $model->items);
        $model->populateRelation('payments', $model->payments);

        return $this->render('view', ['model' => $model]);
    }

    public function actionCreate(): Response|string
    {
        $form = new InvoiceForm();
        $form->invoice_date = date('Y-m-d');

        if (\Yii::$app->request->isPost) {
            $post = \Yii::$app->request->post();
            $form->load($post, 'InvoiceForm');
            $form->items = $post['items'] ?? [];

            if ($form->validate()) {
                try {
                    $invoice = $this->service->createInvoice(
                        $form->getAttributes(['customer_id', 'customer_plan_id', 'invoice_date', 'due_date', 'gst_rate', 'discount_amount', 'notes']),
                        $form->items
                    );
                    \Yii::$app->session->setFlash('success', "Invoice {$invoice->invoice_number} created.");
                    return $this->redirect(['view', 'id' => $invoice->id]);
                } catch (\Throwable $e) {
                    \Yii::$app->session->setFlash('error', $e->getMessage());
                }
            }
        }

        $customers = Customer::find()->where(['is_active' => 1])->orderBy('name')->all();

        return $this->render('create', ['form' => $form, 'customers' => $customers]);
    }

    /**
     * Record a payment against an invoice (AJAX or form POST).
     */
    public function actionPay(int $id): Response|array
    {
        $invoice = $this->findModel($id);

        if ($invoice->status === Invoice::STATUS_PAID) {
            \Yii::$app->session->setFlash('warning', 'Invoice is already fully paid.');
            return $this->redirect(['view', 'id' => $id]);
        }

        $paymentData = \Yii::$app->request->post();

        if (empty($paymentData['amount'])) {
            \Yii::$app->session->setFlash('error', 'Payment amount is required.');
            return $this->redirect(['view', 'id' => $id]);
        }

        try {
            $this->service->recordPayment($invoice, $paymentData);
            \Yii::$app->session->setFlash('success', 'Payment recorded successfully.');
        } catch (\Throwable $e) {
            \Yii::$app->session->setFlash('error', 'Payment error: ' . $e->getMessage());
        }

        return $this->redirect(['view', 'id' => $id]);
    }

    /**
     * Cancel an invoice (only if no payments recorded).
     */
    public function actionCancel(int $id): Response
    {
        $invoice = $this->findModel($id);

        if ($invoice->paid_amount > 0) {
            \Yii::$app->session->setFlash('error', 'Cannot cancel an invoice with recorded payments.');
            return $this->redirect(['view', 'id' => $id]);
        }

        $invoice->status = Invoice::STATUS_CANCELLED;
        $invoice->save(false, ['status', 'updated_at']);
        \Yii::$app->session->setFlash('success', 'Invoice cancelled.');

        // Clear dashboard cache
        \Yii::$app->cache->delete('dashboard_stats');

        return $this->redirect(['view', 'id' => $id]);
    }

    /**
     * Outstanding payments report — all unpaid/partial invoices.
     */
    public function actionOutstanding(): string
    {
        $query = Invoice::find()
            ->with(['customer'])
            ->where(['IN', 'status', [Invoice::STATUS_UNPAID, Invoice::STATUS_PARTIAL]])
            ->orderBy(['due_date' => SORT_ASC, 'created_at' => SORT_ASC]);

        $dataProvider = new ActiveDataProvider([
            'query'      => $query,
            'pagination' => ['pageSize' => 30],
        ]);

        $summary = $this->service->getRevenueSummary();

        return $this->render('outstanding', [
            'dataProvider' => $dataProvider,
            'summary'      => $summary,
        ]);
    }

    /**
     * Download Invoice as PDF.
     */
    public function actionPdf(int $id): void
    {
        $invoice = $this->findModel($id);
        $invoice->populateRelation('customer', $invoice->customer);
        $invoice->populateRelation('items', $invoice->items);

        $pdf = new PdfService();
        $pdf->generateInvoicePdf($invoice);
        exit;
    }

    private function findModel(int $id): Invoice
    {
        $model = Invoice::findOne($id);
        if ($model === null) {
            throw new NotFoundHttpException('Invoice not found.');
        }
        return $model;
    }
}
