<?php

namespace App\Exports;

use App\Models\CashRegister;
use Carbon\Carbon;
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 DailyBalanceExport implements FromCollection, WithHeadings, WithTitle, ShouldAutoSize, WithStyles
{
    protected $startDate;
    protected $endDate;
    protected $cashRegisterId;
    protected $dates = [];
    protected $balanceData = [];

    public function __construct($startDate, $endDate, $cashRegisterId = null)
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
        $this->cashRegisterId = $cashRegisterId;
        $this->prepareDates();
        $this->prepareData();
    }

    /**
     * Prepare dates array
     */
    private function prepareDates()
    {
        $period = Carbon::parse($this->startDate)->daysUntil($this->endDate);
        foreach ($period as $date) {
            $this->dates[] = $date->format('Y-m-d');
        }
    }

    /**
     * Prepare balance data
     */
    private function prepareData()
    {
        $cashRegisters = CashRegister::where('company_id', Auth::user()->company_id);

        if ($this->cashRegisterId) {
            $cashRegisters->where('id', $this->cashRegisterId);
        }

        $cashRegisters = $cashRegisters->orderBy('name')->get();

        foreach ($cashRegisters as $register) {
            $this->balanceData[$register->id] = [
                'name' => $register->name,
                'balances' => []
            ];

            foreach ($this->dates as $date) {
                // حساب الرصيد التراكمي حتى هذا التاريخ
                $deposits = $register->transactions()
                    ->where('type', 'deposit')
                    ->whereDate('created_at', '<=', $date)
                    ->sum('amount');

                $withdrawals = $register->transactions()
                    ->where('type', 'withdrawal')
                    ->whereDate('created_at', '<=', $date)
                    ->sum('amount');

                $transfersOut = $register->transactions()
                    ->where('type', 'transfer')
                    ->whereDate('created_at', '<=', $date)
                    ->sum('amount');

                $transfersIn = $register->relatedTransactions()
                    ->where('type', 'transfer')
                    ->whereDate('created_at', '<=', $date)
                    ->sum('amount');

                $balance = $register->initial_balance + $deposits - $withdrawals - $transfersOut + $transfersIn;

                $this->balanceData[$register->id]['balances'][$date] = $balance;
            }
        }
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $data = collect();

        foreach ($this->balanceData as $registerId => $registerData) {
            $row = [
                'name' => $registerData['name']
            ];

            foreach ($this->dates as $date) {
                $row[$date] = $registerData['balances'][$date];
            }

            $data->push((object)$row);
        }

        return $data;
    }

    /**
     * @return array
     */
    public function headings(): array
    {
        $headings = ['الخزينة'];

        foreach ($this->dates as $date) {
            $headings[] = $date;
        }

        return $headings;
    }

    /**
     * @return string
     */
    public function title(): string
    {
        return 'تقرير الرصيد اليومي (' . $this->startDate . ' - ' . $this->endDate . ')';
    }

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