<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class SalesOrder extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    // KONSTANTA STATUS (Anti Hardcode)
    const STATUS_COMPLETED = 'completed';
    const STATUS_PENDING_APPROVAL = 'pending_approval';
    const STATUS_VOID = 'void';
    const STATUS_CREDIT_HOLD = 'credit_hold';

    /**
     * Helper Terpusat: Cek apakah pesanan baru ini melampaui limit kredit
     */
    public static function checkCreditHold($customerId, $newOrderAmount)
    {
        $customer = DB::table('customers')->where('id', $customerId)->first();
        if (!$customer) return ['is_hold' => false, 'message' => ''];

        $isHold = false;
        $messages = [];

        // Hitung total piutang yang masih belum lunas (digunakan untuk hitungan limit)
        $totalDebt = DB::table('sales')
            ->where('customer_id', $customerId)
            ->whereIn('payment_status', ['unpaid', 'partial', 'pending'])
            ->sum(DB::raw('grand_total - COALESCE(paid_amount, 0) - COALESCE(dp_amount, 0)'));

        // ATURAN 1: LEBIH DARI 1 FAKTUR BELUM LUNAS (Jika diaktifkan)
        if (isset($customer->multiple_invoice_hold_active) && $customer->multiple_invoice_hold_active == 1) {
            $unpaidInvoiceCount = DB::table('sales')
                ->where('customer_id', $customerId)
                ->where('payment_status', 'unpaid')
                ->count();

            if ($unpaidInvoiceCount > 1) {
                $isHold = true;
                $messages[] = "Terdapat $unpaidInvoiceCount faktur yang belum lunas.";
            }
        }

        // ATURAN 2: OVER LIMIT NOMINAL (Jika diaktifkan)
        if (isset($customer->credit_limit_active) && $customer->credit_limit_active == 1) {
            if (($newOrderAmount + $totalDebt) > $customer->credit_limit) {
                $isHold = true;
                $messages[] = "Total piutang melampaui limit kredit (Rp" . number_format($customer->credit_limit, 0) . ").";
            }
        }

        return [
            'is_hold' => $isHold,
            'limit' => $customer->credit_limit ?? 0,
            'current_debt' => $totalDebt,
            'total_after_order' => $newOrderAmount + $totalDebt,
            'message' => $isHold ? "CREDIT HOLD: " . implode(" ", $messages) : ""
        ];
    }

    // Relasi ke Cabang Pemesan
    public function branch()
    {
        return $this->belongsTo(Branch::class, 'branch_id');
    }

    // Relasi ke Cabang Pengirim (Fulfillment)
    public function fulfillmentBranch()
    {
        return $this->belongsTo(Branch::class, 'fulfillment_branch_id');
    }

    // Relasi ke Pelanggan
    public function customer()
    {
        return $this->belongsTo(Customer::class, 'customer_id');
    }

    // Relasi ke User / Salesman
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    // Relasi ke Item Pesanan
    public function items()
    {
        return $this->hasMany(SalesOrderItem::class, 'sales_order_id');
    }
}