<?php

namespace App\Http\Controllers;

use App\Models\CashRegister;
use App\Models\CashTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class CashReportController extends Controller
{
    /**
     * عرض صفحة التقارير الرئيسية
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cashRegisters = CashRegister::where('company_id', Auth::user()->company_id)
            ->orderBy('name')
            ->get();

        return view('cash_reports.index', compact('cashRegisters'));
    }

    /**
     * تقرير الحركة اليومية للخزينة
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function dailyMovement(Request $request)
    {
        $date = $request->date ?? now()->format('Y-m-d');
        $cashRegisterId = $request->cash_register_id;

        $query = CashTransaction::where('company_id', Auth::user()->company_id)
            ->whereDate('created_at', $date);

        if ($cashRegisterId) {
            $query->where(function ($q) use ($cashRegisterId) {
                $q->where('cash_register_id', $cashRegisterId)
                    ->orWhere('related_cash_register_id', $cashRegisterId);
            });
        }

        $transactions = $query->with(['cashRegister', 'relatedCashRegister', 'user'])
            ->orderBy('created_at')
            ->get();

        // حساب الإجماليات
        $totals = [
            'deposits' => $transactions->where('type', 'deposit')->sum('amount'),
            'withdrawals' => $transactions->where('type', 'withdrawal')->sum('amount'),
            'transfers_out' => $transactions->where('type', 'transfer')->where('cash_register_id', $cashRegisterId)->sum('amount'),
            'transfers_in' => $transactions->where('type', 'transfer')->where('related_cash_register_id', $cashRegisterId)->sum('amount'),
        ];

        $cashRegisters = CashRegister::where('company_id', Auth::user()->company_id)
            ->orderBy('name')
            ->get();

        $selectedRegister = $cashRegisterId ? CashRegister::find($cashRegisterId) : null;

        return view('cash_reports.daily_movement', compact('transactions', 'cashRegisters', 'selectedRegister', 'date', 'totals'));
    }

    /**
     * تقرير ملخص الخزائن
     *
     * @return \Illuminate\Http\Response
     */
    public function cashRegistersSummary()
    {
        $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 view('cash_reports.registers_summary', compact('cashRegisters'));
    }

    /**
     * تقرير المعاملات حسب الفترة
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function transactionsByPeriod(Request $request)
    {
        $startDate = $request->start_date ?? now()->startOfMonth()->format('Y-m-d');
        $endDate = $request->end_date ?? now()->format('Y-m-d');
        $cashRegisterId = $request->cash_register_id;
        $type = $request->type;

        $query = CashTransaction::where('company_id', Auth::user()->company_id)
            ->whereDate('created_at', '>=', $startDate)
            ->whereDate('created_at', '<=', $endDate);

        if ($cashRegisterId) {
            $query->where(function ($q) use ($cashRegisterId) {
                $q->where('cash_register_id', $cashRegisterId)
                    ->orWhere('related_cash_register_id', $cashRegisterId);
            });
        }

        if ($type) {
            $query->where('type', $type);
        }

        $transactions = $query->with(['cashRegister', 'relatedCashRegister', 'user'])
            ->orderBy('created_at', 'desc')
            ->get();

        // حساب الإجماليات
        $totals = [
            'deposits' => $transactions->where('type', 'deposit')->sum('amount'),
            'withdrawals' => $transactions->where('type', 'withdrawal')->sum('amount'),
            'transfers' => $transactions->where('type', 'transfer')->sum('amount'),
            'total' => $transactions->where('type', 'deposit')->sum('amount') -
                $transactions->where('type', 'withdrawal')->sum('amount')
        ];

        $cashRegisters = CashRegister::where('company_id', Auth::user()->company_id)
            ->orderBy('name')
            ->get();

        return view('cash_reports.transactions_by_period', compact('transactions', 'cashRegisters', 'startDate', 'endDate', 'cashRegisterId', 'type', 'totals'));
    }

    /**
     * تقرير الرصيد اليومي للخزائن
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function dailyBalance(Request $request)
    {
        $startDate = $request->start_date ?? now()->subDays(30)->format('Y-m-d');
        $endDate = $request->end_date ?? now()->format('Y-m-d');
        $cashRegisterId = $request->cash_register_id;

        $cashRegisters = CashRegister::where('company_id', Auth::user()->company_id);

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

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

        // إنشاء مصفوفة للتواريخ
        $period = Carbon::parse($startDate)->daysUntil($endDate);
        $dates = [];
        foreach ($period as $date) {
            $dates[] = $date->format('Y-m-d');
        }

        // الحصول على بيانات الرصيد لكل خزينة في كل يوم
        $balanceData = [];

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

            $balance = $register->initial_balance;

            foreach ($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;

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

        return view('cash_reports.daily_balance', compact('cashRegisters', 'dates', 'balanceData', 'startDate', 'endDate', 'cashRegisterId'));
    }

    /**
     * تصدير تقرير إلى Excel
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function exportToExcel(Request $request)
    {
        $reportType = $request->report_type;
        $startDate = $request->start_date;
        $endDate = $request->end_date;
        $cashRegisterId = $request->cash_register_id;
        $type = $request->type;
        $date = $request->date;

        switch ($reportType) {
            case 'daily_movement':
                return \Maatwebsite\Excel\Facades\Excel::download(
                    new \App\Exports\DailyMovementExport($date, $cashRegisterId),
                    'daily_movement_' . $date . '.xlsx'
                );

            case 'registers_summary':
                return \Maatwebsite\Excel\Facades\Excel::download(
                    new \App\Exports\RegistersSummaryExport(),
                    'registers_summary_' . now()->format('Y-m-d') . '.xlsx'
                );

            case 'transactions_by_period':
                return \Maatwebsite\Excel\Facades\Excel::download(
                    new \App\Exports\TransactionsByPeriodExport($startDate, $endDate, $cashRegisterId, $type),
                    'transactions_' . $startDate . '_to_' . $endDate . '.xlsx'
                );

            case 'daily_balance':
                return \Maatwebsite\Excel\Facades\Excel::download(
                    new \App\Exports\DailyBalanceExport($startDate, $endDate, $cashRegisterId),
                    'daily_balance_' . $startDate . '_to_' . $endDate . '.xlsx'
                );

            default:
                return redirect()->back()->with('error', 'نوع التقرير غير صالح');
        }
    }
}
