<?php

namespace App\Models;

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

class PayrollPeriod extends Model
{
    use HasFactory;

    protected $fillable = [
        'company_id',
        'financial_year_id',
        'period_name',
        'period_type',
        'start_date',
        'end_date',
        'payment_date',
        'cutoff_date',
        'status',
        'is_active',
        'created_by',
        'updated_by'
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'payment_date' => 'date',
        'cutoff_date' => 'date',
        'is_active' => 'boolean'
    ];

    // Relationships (keep the same)
    public function company()
    {
        return $this->belongsTo(Company::class, 'company_id');
    }

    public function financialYear()
    {
        return $this->belongsTo(FinancialYear::class, 'financial_year_id');
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    // Scopes
    public function scopeForCompany($query, $companyId)
    {
        return $query->where('company_id', $companyId);
    }

    public function scopeForFinancialYear($query, $financialYearId)
    {
        return $query->where('financial_year_id', $financialYearId);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeOpen($query)
    {
        return $query->where('status', 'open');
    }

    public function scopeClosed($query)
    {
        return $query->where('status', 'closed');
    }

    public function scopeProcessing($query)
    {
        return $query->where('status', 'processing');
    }

    public function scopeMonthly($query)
    {
        return $query->where('period_type', 'monthly');
    }

    // Helper methods
    public function getPeriodTypeNameAttribute()
    {
        return 'Monthly'; // Always monthly
    }

    public function getStatusBadgeAttribute()
    {
        $badges = [
            'open' => '<span class="quickbooks-badge bg-green-100 text-green-800">Open</span>',
            'closed' => '<span class="quickbooks-badge bg-gray-100 text-gray-800">Closed</span>',
            'processing' => '<span class="quickbooks-badge bg-yellow-100 text-yellow-800">Processing</span>'
        ];

        return $badges[$this->status] ?? '<span class="quickbooks-badge bg-gray-100 text-gray-800">Unknown</span>';
    }

    public function getFormattedDateRangeAttribute()
    {
        return $this->start_date->format('M d, Y') . ' - ' . $this->end_date->format('M d, Y');
    }

    public function getMonthNameAttribute()
    {
        return $this->start_date->format('F Y');
    }

    public function canProcessPayroll()
    {
        return $this->status === 'open' && $this->is_active;
    }

    public function closePeriod()
    {
        $this->update(['status' => 'closed']);
    }

    public function reopenPeriod()
    {
        $this->update(['status' => 'open']);
    }

    // Generate period name automatically based on date
    public static function generatePeriodName($startDate)
    {
        $date = \Carbon\Carbon::parse($startDate);
        return $date->format('F Y') . ' Payroll';
    }

    // Auto-generate monthly periods for a financial year
    public static function generateMonthlyPeriods($companyId, $financialYearId, $financialYear)
    {
        $periods = [];
        $startDate = \Carbon\Carbon::parse($financialYear->start_date);
        $endDate = \Carbon\Carbon::parse($financialYear->end_date);
        
        $current = $startDate->copy();
        
        while ($current <= $endDate) {
            $periodStart = $current->copy();
            $periodEnd = $current->copy()->endOfMonth();
            
            // Adjust if period end exceeds financial year end
            if ($periodEnd > $endDate) {
                $periodEnd = $endDate;
            }
            
            // Cutoff date: 25th of the month
            $cutoffDate = $periodStart->copy()->day(25);
            if ($cutoffDate < $periodStart) {
                $cutoffDate = $periodStart;
            }
            
            // Payment date: 5th of next month
            $paymentDate = $periodEnd->copy()->addDays(5);
            
            $periods[] = [
                'company_id' => $companyId,
                'financial_year_id' => $financialYearId,
                'period_name' => self::generatePeriodName($periodStart),
                'period_type' => 'monthly',
                'start_date' => $periodStart->format('Y-m-d'),
                'end_date' => $periodEnd->format('Y-m-d'),
                'cutoff_date' => $cutoffDate->format('Y-m-d'),
                'payment_date' => $paymentDate->format('Y-m-d'),
                'status' => $periodEnd < now() ? 'closed' : 'open',
                'is_active' => true,
                'created_by' => auth()->id(),
                'created_at' => now(),
                'updated_at' => now()
            ];
            
            $current = $periodEnd->copy()->addDay();
        }
        
        return $periods;
    }
}