<?php

namespace PortalPeople\creditnotes\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "credit_notes".
 *
 * @property int $id
 * @property int $entity_id
 * @property string $entity_type
 * @property string $credit_note_number
 * @property float $amount
 * @property string $reason
 * @property string $status
 * @property string $created_at
 * @property string $created_by
 * @property string $notes
 */
class CreditNote extends ActiveRecord
{
    const STATUS_DRAFT = 'Draft';
    const STATUS_ISSUED = 'Issued';
    const STATUS_CANCELLED = 'Cancelled';

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'credit_notes';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['entity_id', 'entity_type', 'amount', 'reason'], 'required'],
            [['entity_id'], 'integer'],
            [['amount'], 'number', 'min' => 0],
            [['credit_note_number', 'reason', 'notes', 'status', 'entity_type'], 'string'],
            [['created_at'], 'safe'],
            [['created_by'], 'string'],
            [['status'], 'default', 'value' => self::STATUS_DRAFT],
            [['created_at'], 'default', 'value' => function() { return date('Y-m-d H:i:s'); }],
            [['created_by'], 'default', 'value' => function() { return Yii::$app->user->identity?->id ?? 'system'; }],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'entity_id' => 'Entity ID',
            'entity_type' => 'Entity Type',
            'credit_note_number' => 'Credit Note Number',
            'amount' => 'Amount',
            'reason' => 'Reason',
            'status' => 'Status',
            'created_at' => 'Created At',
            'created_by' => 'Created By',
            'notes' => 'Notes',
        ];
    }

    /**
     * Generate credit note number
     *
     * @return string
     */
    public function generateCreditNoteNumber(): string
    {
        $date = date('Ymd');
        $id = str_pad($this->id ?? 0, 5, '0', STR_PAD_LEFT);
        return "CN-{$date}-{$id}";
    }

    /**
     * Check if credit note can be issued
     *
     * @return bool
     */
    public function canIssue(): bool
    {
        return $this->status === self::STATUS_DRAFT && $this->validate();
    }

    /**
     * Issue the credit note
     *
     * @return bool
     */
    public function issue(): bool
    {
        if (!$this->canIssue()) {
            return false;
        }

        $this->status = self::STATUS_ISSUED;
        $this->credit_note_number = $this->generateCreditNoteNumber();
        return $this->save(false);
    }
}
