<?php

namespace App\Exports;

use App\Models\Employee;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class EmployeeExport implements FromCollection, WithHeadings
{
    /**
     * Full download URL for picture / file / attachment / video paths (stored under public/images/).
     */
    protected function exportMediaUrl($path): string
    {
        if ($path === null || trim((string) $path) === '') {
            return '';
        }
        $path = strip_tags((string) $path);
        if (preg_match('#^https?://#i', $path)) {
            return $path;
        }
        return rtrim(config('app.url'), '/') . '/images/' . ltrim($path, '/');
    }

    /**
     * Headings for the export.
     */
    public function headings(): array
    {
        return ['Sr.', 'Employee Code', 'First Name', 'Last Name', 'Email', 'Phone', 'Cnic', 'Gender', 'Date Of Birth', 'Joining Date', 'Department', 'Designation', 'Shift', 'Employment Type', 'Basic Salary', 'Bank Name', 'Bank Account Number', 'Address', 'Profile Picture', 'Resume', 'Skills', 'Status', 'Client'];
    }

    /**
     * Collection of rows for Excel export.
     */
    public function collection()
    {
        $data = Employee::with(['department', 'designation', 'shift', 'client'])
->latest('client_id')
->whereNull('deleted_at')
->get();

        // Add serial numbers
        $sr = 1;
        return $data->map(function ($row) use (&$sr) {
            return [
                $sr++,
                strip_tags($row->employee_code), strip_tags($row->first_name), strip_tags($row->last_name), strip_tags($row->email), strip_tags($row->phone), strip_tags($row->cnic), strip_tags($row->gender), strip_tags($row->date_of_birth), strip_tags($row->joining_date), strip_tags($row->department ? $row->department->name : ''), strip_tags($row->designation ? $row->designation->name : ''), strip_tags($row->shift ? $row->shift->name : ''), strip_tags($row->employment_type), strip_tags($row->basic_salary), strip_tags($row->bank_name), strip_tags($row->bank_account_number), strip_tags($row->address), $this->exportMediaUrl($row->profile_picture), strip_tags($row->resume), strip_tags($row->skills), strip_tags($row->status), strip_tags($row->client ? $row->client->name : '')
            ];
        });
    }
}
