<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Revenue extends Model
{
    protected $table = 'revenue';
    protected $primaryKey = 'revenue_id';
    public $incrementing = true;
    public $timestamps = true;

    protected $fillable = [
        'txn_id',
        'ticket_price',
        'federation_share',
        'developer_share',
        'ticket_price',
    ];

    protected $casts = [
        'federation_share' => 'decimal:2',
        'developer_share' => 'decimal:2',
        'ticket_price' => 'decimal:2',
    ];

    /**
     * Calculate shares based on ticket price
     * Developer gets 20%, Federation gets 80%
     */
    public static function calculateShares($ticketPrice)
    {
        return [
            'developer_share' => $ticketPrice * 0.20,
            'federation_share' => $ticketPrice * 0.80,
        ];
    }

    /**
     * Create revenue record from transaction
     */
    public static function createFromTransaction($txnId, $ticketPrice)
    {
        $shares = self::calculateShares($ticketPrice);

        return self::create([
            'txn_id' => $txnId,
            'ticket_price' => $ticketPrice,
            'developer_share' => $shares['developer_share'],
            'federation_share' => $shares['federation_share'],
        ]);
    }

    /**
     * Get total revenue for a period
     */
    public static function getTotalRevenue($startDate = null, $endDate = null)
    {
        $query = self::query();

        if ($startDate) {
            $query->where('created_at', '>=', $startDate);
        }

        if ($endDate) {
            $query->where('created_at', '<=', $endDate);
        }

        return $query->sum('ticket_price');
    }

    /**
     * Get developer total share
     */
    public static function getDeveloperTotal($startDate = null, $endDate = null)
    {
        $query = self::query();

        if ($startDate) {
            $query->where('created_at', '>=', $startDate);
        }

        if ($endDate) {
            $query->where('created_at', '<=', $endDate);
        }

        return $query->sum('developer_share');
    }

    /**
     * Get federation total share
     */
    public static function getFederationTotal($startDate = null, $endDate = null)
    {
        $query = self::query();

        if ($startDate) {
            $query->where('created_at', '>=', $startDate);
        }

        if ($endDate) {
            $query->where('created_at', '<=', $endDate);
        }

        return $query->sum('federation_share');
    }

    public function transaction()
    {
        return $this->belongsTo(\App\Models\TransactionModel::class, 'txn_id', 'txn_id');
    }
}
