<?php

namespace App\Models;

use App\Models\Traits\HasAuditFields;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class ManufacturingPlan extends Model
{
    use HasFactory, SoftDeletes, HasAuditFields;

    protected $table = 'manufacturing_plans';

    /**
     * Status constants
     */
    public const STATUS_DRAFT = 'draft';
    public const STATUS_READY_TO_PLAN = 'Ready to plan';
    public const STATUS_PLANNED = 'Planned';
    public const STATUS_RUNNING = 'running';
    public const STATUS_MAINTENANCE = 'maintenance';
    public const STATUS_ISSUE = 'issue';
    public const STATUS_COMPLETED = 'completed';

    protected $fillable = [
        'rc_id',
        'company_name',
        'status',
        'rc_date',
        'approved_by',
        'plan_by',
        'plan_date',
        'machine',
        'process',
        'operator',
        'ct_hours',
        'ct_minutes',
        'start_date',
        'end_date',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'rc_date' => 'date',
        'plan_date' => 'date',
        'start_date' => 'datetime',
        'end_date' => 'datetime',
        'ct_hours' => 'integer',
        'ct_minutes' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    // ──────────────────────────────────────────────────────────────────────────
    // RELATIONSHIPS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Get the route card associated with this plan.
     */
    public function routeCard()
    {
        return $this->belongsTo(RouteCard::class, 'rc_id');
    }

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

    /**
     * Get the user who approved this plan.
     */
    public function approver()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    /**
     * Get the planner (user who planned).
     */
    public function planner()
    {
        return $this->belongsTo(User::class, 'plan_by');
    }

    /**
     * Get the operator assigned.
     */
    public function assignedOperator()
    {
        return $this->belongsTo(EmployeeDetails::class, 'operator');
    }

    /**
     * Get the machine assigned.
     */
    public function assignedMachine()
    {
        return $this->belongsTo(Machines::class, 'machine');
    }

    // ──────────────────────────────────────────────────────────────────────────
    // SCOPES
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Filter by draft status
     */
    public function scopeDraft(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_DRAFT);
    }

    /**
     * Filter by ready to plan status
     */
    public function scopeReadyToPlan(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_READY_TO_PLAN);
    }

    /**
     * Filter by planned status
     */
    public function scopePlanned(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_PLANNED);
    }

    /**
     * Filter by running status
     */
    public function scopeRunning(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_RUNNING);
    }

    /**
     * Filter by completed status
     */
    public function scopeCompleted(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_COMPLETED);
    }

    /**
     * Filter active plans (not completed)
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query->whereNotIn('status', [self::STATUS_COMPLETED]);
    }

    /**
     * Filter by machine
     */
    public function scopeForMachine(Builder $query, $machineId): Builder
    {
        return $query->where('machine', $machineId);
    }

    /**
     * Filter by operator
     */
    public function scopeForOperator(Builder $query, $operatorId): Builder
    {
        return $query->where('operator', $operatorId);
    }

    /**
     * Filter by date range
     */
    public function scopeScheduledBetween(Builder $query, $startDate, $endDate): Builder
    {
        return $query->whereBetween('start_date', [$startDate, $endDate]);
    }

    // ──────────────────────────────────────────────────────────────────────────
    // ACCESSORS & HELPERS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Get all valid statuses
     */
    public static function getStatuses(): array
    {
        return [
            self::STATUS_DRAFT,
            self::STATUS_READY_TO_PLAN,
            self::STATUS_PLANNED,
            self::STATUS_RUNNING,
            self::STATUS_MAINTENANCE,
            self::STATUS_ISSUE,
            self::STATUS_COMPLETED,
        ];
    }

    /**
     * Get total cycle time in minutes
     */
    public function getCycleTimeInMinutes(): int
    {
        return (($this->ct_hours ?? 0) * 60) + ($this->ct_minutes ?? 0);
    }

    /**
     * Get formatted cycle time
     */
    public function getFormattedCycleTime(): string
    {
        $hours = $this->ct_hours ?? 0;
        $minutes = $this->ct_minutes ?? 0;

        if ($hours > 0) {
            return "{$hours}h {$minutes}m";
        }

        return "{$minutes}m";
    }

    /**
     * Check if plan is running
     */
    public function isRunning(): bool
    {
        return $this->status === self::STATUS_RUNNING;
    }

    /**
     * Check if plan is completed
     */
    public function isCompleted(): bool
    {
        return $this->status === self::STATUS_COMPLETED;
    }

    /**
     * Check if plan has issues
     */
    public function hasIssues(): bool
    {
        return in_array($this->status, [self::STATUS_ISSUE, self::STATUS_MAINTENANCE]);
    }
}
