<?php

namespace App\Exports;

use App\Models\WorkOrder;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Illuminate\Support\Facades\Auth;

class WorkOrdersExport implements FromCollection, WithHeadings, WithMapping
{
    protected $request;

    public function __construct($request = null)
    {
        $this->request = $request;
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $companyId = Auth::user()->company_id;
        $query = WorkOrder::where('company_id', $companyId)
            ->with(['elevator.customer', 'elevatorStage', 'technician'])
            ->orderBy('created_at', 'desc');

        if ($this->request) {
            if ($this->request->filled('elevator_number')) {
                $query->whereHas('elevator', function ($q) {
                    $q->where('serial_number', 'like', '%' . $this->request->elevator_number . '%')
                      ->orWhere('model', 'like', '%' . $this->request->elevator_number . '%');
                });
            }

            if ($this->request->filled('customer_name')) {
                $query->whereHas('elevator.customer', function ($q) {
                    $q->where('name', 'like', '%' . $this->request->customer_name . '%');
                });
            }

            if ($this->request->filled('stage_name')) {
                $query->where('elevator_stage_id', $this->request->stage_name);
            }

            if ($this->request->filled('status')) {
                $query->where('status', $this->request->status);
            }
        }

        return $query->get();
    }

    public function headings(): array
    {
        return [
            '#',
            'المصعد',
            'العميل',
            'مرحلة المصعد',
            'الفني المسؤول',
            'الحالة',
            'تاريخ الأمر',
            'تاريخ الاستلام',
            'تاريخ الإنجاز',
        ];
    }

    public function map($workOrder): array
    {
        return [
            $workOrder->id,
            $workOrder->elevator ? ($workOrder->elevator->model . ' - ' . $workOrder->elevator->serial_number) : '',
            ($workOrder->elevator && $workOrder->elevator->customer) ? $workOrder->elevator->customer->name : '',
            $workOrder->elevatorStage ? $workOrder->elevatorStage->name : '',
            $workOrder->technician ? $workOrder->technician->name : '',
            $workOrder->status_text,
            $workOrder->order_date ? $workOrder->order_date->format('Y-m-d') : '',
            $workOrder->received_date ? $workOrder->received_date->format('Y-m-d') : '',
            $workOrder->completion_date ? $workOrder->completion_date->format('Y-m-d') : '',
        ];
    }
}
