<?php

namespace App\Modules\Hr\Services;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

abstract class BaseExport implements FromArray, WithHeadings, WithTitle, WithStyles, WithColumnWidths
{
    protected $data;
    protected $user_details;
    protected $start;
    protected $end;
    protected $total_hours;
    protected $total_money;
    protected $originalStart;
    protected $originalEnd;

    public function __construct($data, $user_details, $start, $end, $total_hours, $total_money, $originalStart = null, $originalEnd = null)
    {
        $this->data = $data;
        $this->user_details = $user_details;
        $this->start = $start;
        $this->end = $end;
        $this->total_hours = $total_hours;
        $this->total_money = $total_money;
        
        // Use original dates for display, fallback to processed dates if not provided
        $this->originalStart = $originalStart ?: $start;
        $this->originalEnd = $originalEnd ?: $end;
    }

    public function headings(): array
    {
        return [];
    }

    /**
     * Get the header rows for the export
     *
     * @return array
     */
    protected function getHeaderRows(): array
    {
        return [
            [trim($this->user_details->user->name) . ' - Interval: ' . date('d/m/Y', strtotime($this->originalStart)) . ' - ' . date('d/m/Y', strtotime($this->originalEnd))],
            ['ID', 'Date', 'Clocked In', 'Clocked Out', 'Hours', 'Total']
        ];
    }

    /**
     * Get the total rows for the export
     *
     * @return array
     */
    protected function getTotalRows(): array
    {
        return [
            [], // blank row
            [null, null, null, null, $this->total_hours, $this->total_money]
        ];
    }

    /**
     * Apply common header styling
     *
     * @param Worksheet $sheet
     * @return void
     */
    protected function applyHeaderStyling(Worksheet $sheet): void
    {
        // Style the header (name and interval combined) - Row 1
        $sheet->getStyle('A1:F1')->applyFromArray([
            'font' => [
                'bold' => true,
                'size' => 14,
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
            ],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'startColor' => ['rgb' => 'D9EDF7'] // Light blue background
            ]
        ]);
        $sheet->mergeCells('A1:F1'); // Merge all cells for combined header
        
        // Style the column headers - Row 2
        $sheet->getStyle('A2:F2')->applyFromArray([
            'font' => [
                'bold' => true,
                'size' => 12,
            ],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'startColor' => ['rgb' => 'E6E6E6']
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
            ],
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['rgb' => '000000']
                ]
            ]
        ]);
    }

    /**
     * Apply common data row styling
     *
     * @param Worksheet $sheet
     * @param int $dataRowCount
     * @return void
     */
    protected function applyDataRowStyling(Worksheet $sheet, int $dataRowCount): void
    {
        $dataStartRow = 3;
        $dataEndRow = $dataStartRow + $dataRowCount - 1;
        
        if ($dataRowCount > 0) {
            $sheet->getStyle("A{$dataStartRow}:F{$dataEndRow}")->applyFromArray([
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => Border::BORDER_THIN,
                        'color' => ['rgb' => 'CCCCCC']
                    ]
                ],
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                ],
            ]);
            
            // Right align the Hours and Total columns
            $sheet->getStyle("E{$dataStartRow}:F{$dataEndRow}")->getAlignment()
                ->setHorizontal(Alignment::HORIZONTAL_RIGHT);
        }
    }

    /**
     * Apply common total row styling
     *
     * @param Worksheet $sheet
     * @param int $totalRows
     * @return void
     */
    protected function applyTotalRowStyling(Worksheet $sheet, int $totalRows): void
    {
        $sheet->getStyle("A{$totalRows}:F{$totalRows}")->applyFromArray([
            'font' => [
                'bold' => true,
                'size' => 12,
            ],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'startColor' => ['rgb' => 'F0F0F0']
            ],
            'borders' => [
                'top' => [
                    'borderStyle' => Border::BORDER_THICK,
                    'color' => ['rgb' => '000000']
                ]
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_RIGHT,
            ],
        ]);
    }

    /**
     * Apply number formatting to columns
     *
     * @param Worksheet $sheet
     * @param int $dataRowCount
     * @return void
     */
    protected function applyNumberFormatting(Worksheet $sheet, int $dataRowCount): void
    {
        $dataStartRow = 3;
        $dataEndRow = $dataStartRow + $dataRowCount - 1;
        
        if ($dataRowCount > 0) {
            // Format time columns as time
            $sheet->getStyle("C{$dataStartRow}:D{$dataEndRow}")
                ->getNumberFormat()
                ->setFormatCode('HH:MM:SS');
            
            // Format numbers in Hours and Total columns
            $sheet->getStyle("E{$dataStartRow}:E{$dataEndRow}")
                ->getNumberFormat()
                ->setFormatCode('0.00');
            $sheet->getStyle("F{$dataStartRow}:F{$dataEndRow}")
                ->getNumberFormat()
                ->setFormatCode('0.00');
        }
    }
} 