<?php

namespace App\Exports;

use App\Models\CashRegister;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class RegistersSummaryExport implements FromCollection, WithHeadings, WithMapping, WithTitle, ShouldAutoSize, WithStyles
{
    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $cashRegisters = CashRegister::where('company_id', Auth::user()->company_id)
            ->with(['responsibleUser'])
            ->orderBy('name')
            ->get();

        // حساب إجماليات المعاملات لكل خزينة
        foreach ($cashRegisters as $register) {
            $register->total_deposits = $register->transactions()->where('type', 'deposit')->sum('amount');
            $register->total_withdrawals = $register->transactions()->where('type', 'withdrawal')->sum('amount');
            $register->total_transfers_out = $register->transactions()->where('type', 'transfer')->sum('amount');
            $register->total_transfers_in = $register->relatedTransactions()->where('type', 'transfer')->sum('amount');
        }

        return $cashRegisters;
    }

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

    /**
     * @param mixed $row
     *
     * @return array
     */
    public function map($register): array
    {
        static $i = 0;
        $i++;

        $currentBalance = $register->initial_balance + $register->total_deposits - $register->total_withdrawals - $register->total_transfers_out + $register->total_transfers_in;

        return [
            $i,
            $register->name,
            $register->code,
            $register->responsibleUser ? $register->responsibleUser->name : '-',
            $register->initial_balance,
            $register->total_deposits,
            $register->total_withdrawals,
            $register->total_transfers_out,
            $register->total_transfers_in,
            $currentBalance,
            $register->currency
        ];
    }

    /**
     * @return string
     */
    public function title(): string
    {
        return 'تقرير ملخص الخزائن';
    }

    /**
     * @param Worksheet $sheet
     */
    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true]],
        ];
    }
}
