<?php

/**
 * File: app/Models/BackOfficeTransaction.php
 * 
 * Model untuk mengelola transaksi back office (pemasukan & pengeluaran)
 * yang bukan dari penjualan/pembelian produk utama
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class BackOfficeTransaction extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The table associated with the model.
     */
    protected $table = 'back_office_transactions';

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'type',
        'category',
        'description',
        'amount',
        'transaction_date',
        'reference_number',
        'notes',
        'attachment',
        'created_by',
    ];

    /**
     * The attributes that should be cast.
     */
    protected $casts = [
        'transaction_date' => 'date',
        'amount' => 'decimal:2',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    // ============================================
    // KATEGORI PEMASUKAN
    // ============================================
    public static $incomeCategories = [
        'scrap_sale' => 'Penjualan Scrap/Limbah',
        'service' => 'Jasa Service/Perbaikan',
        'rent' => 'Pendapatan Sewa',
        'sparepart_sale' => 'Penjualan Sparepart',
        'interest' => 'Bunga Bank',
        'subsidy' => 'Subsidi/Hibah',
        'asset_sale' => 'Penjualan Aset',
        'other_income' => 'Pemasukan Lainnya',
    ];

    // ============================================
    // KATEGORI PENGELUARAN
    // ============================================
    public static $expenseCategories = [
        'salary' => 'Gaji Karyawan',
        'electricity' => 'Listrik',
        'water' => 'Air',
        'internet' => 'Internet/Telepon',
        'maintenance' => 'Maintenance Mesin',
        'fuel' => 'BBM/Transportasi',
        'office_supplies' => 'ATK (Alat Tulis Kantor)',
        'tax' => 'Pajak/Perizinan',
        'rent' => 'Sewa Gedung',
        'marketing' => 'Marketing/Iklan',
        'consumption' => 'Konsumsi',
        'security' => 'Keamanan',
        'cleaning' => 'Kebersihan',
        'other_expense' => 'Pengeluaran Lainnya',
    ];

    // ============================================
    // RELATIONSHIPS
    // ============================================

    /**
     * Get the user who created this transaction
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    // ============================================
    // SCOPES
    // ============================================

    /**
     * Scope untuk filter pemasukan saja
     */
    public function scopeIncome($query)
    {
        return $query->where('type', 'income');
    }

    /**
     * Scope untuk filter pengeluaran saja
     */
    public function scopeExpense($query)
    {
        return $query->where('type', 'expense');
    }

    /**
     * Scope untuk filter berdasarkan range tanggal
     */
    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('transaction_date', [$startDate, $endDate]);
    }

    /**
     * Scope untuk filter berdasarkan kategori
     */
    public function scopeByCategory($query, $category)
    {
        return $query->where('category', $category);
    }

    /**
     * Scope untuk search berdasarkan deskripsi atau nomor referensi
     */
    public function scopeSearch($query, $search)
    {
        return $query->where(function ($q) use ($search) {
            $q->where('description', 'like', "%{$search}%")
                ->orWhere('reference_number', 'like', "%{$search}%");
        });
    }

    // ============================================
    // ACCESSORS (Getter)
    // ============================================

    /**
     * Get nama kategori dalam Bahasa Indonesia
     */
    public function getCategoryNameAttribute()
    {
        if ($this->type === 'income') {
            return self::$incomeCategories[$this->category] ?? $this->category;
        }
        return self::$expenseCategories[$this->category] ?? $this->category;
    }

    /**
     * Get formatted amount (Rupiah format)
     */
    public function getFormattedAmountAttribute()
    {
        return 'Rp ' . number_format($this->amount, 0, ',', '.');
    }

    /**
     * Get attachment URL
     */
    public function getAttachmentUrlAttribute()
    {
        if ($this->attachment) {
            return asset('storage/' . $this->attachment);
        }
        return null;
    }

    /**
     * Get type label in Indonesian
     */
    public function getTypeLabelAttribute()
    {
        return $this->type === 'income' ? 'Pemasukan' : 'Pengeluaran';
    }

    // ============================================
    // HELPER METHODS
    // ============================================

    /**
     * Check if transaction is income
     */
    public function isIncome()
    {
        return $this->type === 'income';
    }

    /**
     * Check if transaction is expense
     */
    public function isExpense()
    {
        return $this->type === 'expense';
    }

    /**
     * Get total income by date range
     */
    public static function getTotalIncome($startDate = null, $endDate = null)
    {
        $query = self::income();

        if ($startDate && $endDate) {
            $query->byDateRange($startDate, $endDate);
        }

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

    /**
     * Get total expense by date range
     */
    public static function getTotalExpense($startDate = null, $endDate = null)
    {
        $query = self::expense();

        if ($startDate && $endDate) {
            $query->byDateRange($startDate, $endDate);
        }

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

    /**
     * Get net income (income - expense)
     */
    public static function getNetIncome($startDate = null, $endDate = null)
    {
        $income = self::getTotalIncome($startDate, $endDate);
        $expense = self::getTotalExpense($startDate, $endDate);

        return $income - $expense;
    }
}
