<?php

namespace App\Http\Controllers\User;

use App\Models\Sale;
use App\Models\Work;
use App\Models\Service;
use App\Models\Purchase;
use App\Models\Subscriber;
use App\Models\Transaction;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Request as SiteRequest;

class UserController extends Controller
{
    //
    public function dashboard(){



        return view('user.dashboard' );
      }

    public function stats(Request $request)
        {
            $user = auth()->user();
            if (!$user) {
                abort(403, 'لا يوجد مستخدم.');
            }

            $from = $request->from;
            $to   = $request->to;

            // 🧭 الفلترة بالتاريخ
            $dateFilter = function ($q) use ($from, $to) {
                $q->when(!empty($from) && !empty($to), fn($x) => $x->whereBetween('created_at', [$from . ' 00:00:00', $to . ' 23:59:59']))
                ->when(!empty($from) && empty($to), fn($x) => $x->whereDate('created_at', '>=', $from))
                ->when(!empty($to) && empty($from), fn($x) => $x->whereDate('created_at', '<=', $to));
            };

            // ✅ إجمالي المبيعات من جدول sales
            $total_sale_amount = Sale::where('user_id', $user->id)
                ->where($dateFilter)
                ->sum('total_amount');

            // ✅ إجمالي المشتريات من جدول purchases
            $total_purchase_amount = Purchase::where('user_id', $user->id)
                ->where($dateFilter)
                ->sum('total_amount');

            // ✅ إجمالي الدفعات الصادرة من جدول transactions
            $total_payment = Transaction::where('user_id', $user->id)
                ->whereIn('type', ['sale', 'payment'])
                ->where($dateFilter)
                ->sum('paid_amount');

            // ✅ إجمالي الدفعات الواردة من جدول transactions
            $total_supplier_payment = Transaction::where('user_id', $user->id)
                ->whereIn('type', ['purchase', 'supplier_payment'])
                ->where($dateFilter)
                ->sum('paid_amount');

            // ✅ الإرجاع على شكل JSON
            return response()->json([
                'total_sale_amount' => $total_sale_amount,
                'total_purchase_amount' => $total_purchase_amount,
                'total_payment' => $total_payment,
                'total_supplier_payment' => $total_supplier_payment,
            ]);
        }
}
