<?php

namespace Workdo\MobileServiceManagement\Http\Controllers;

use App\Models\Invoice;
use App\Models\InvoicePayment;
use App\Models\WorkSpace;

use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;

use Workdo\MobileServiceManagement\Entities\MobileServiceRequest;

class MobileServiceDashboardController extends Controller
{
    public function __construct()
    {
        if (module_is_active('GoogleAuthentication')) {
            $this->middleware('2fa');
        }
    }

    public function index()
    {
        if (Auth::user()->isAbleTo('mobileservice dashboard manage')) {
            $workspace = WorkSpace::where('id', getActiveWorkSpace())
                ->where('created_by', creatorId())
                ->first();

            // Basic counts
            $pendingRequest = MobileServiceRequest::where('is_approve', null)
                ->where('workspace_id', getActiveWorkSpace())
                ->count();

            $allRequest = MobileServiceRequest::where('is_approve', 1)
                ->where('is_repair_end', 0)
                ->where('workspace_id', getActiveWorkSpace())
                ->count();

            $totalCompletedRequest = MobileServiceRequest::where('is_repair_end', 1)
                ->where('workspace_id', getActiveWorkSpace())
                ->count();

            $totalIncome = 0;
            $invoices    = Invoice::where('invoice_module', 'mobileservice')
                ->where('workspace', getActiveWorkSpace())
                ->get();
            foreach ($invoices as $invoice) {
                $getInvoicePayments = InvoicePayment::where('invoice_id', $invoice->id)->get();
                foreach ($getInvoicePayments as $payment) {
                    $totalIncome += $payment->amount;
                }
            }

            // Recent requests with relationships
            $recentRequests = MobileServiceRequest::with([
                'getInvoiceStatus',
                'getServiceCreatedName',
                'getAssignTechnician.getTechnicianDetails',
                'deviceBrand',
                'service'
            ])
                ->where('workspace_id', getActiveWorkSpace())
                ->orderby('created_at', 'desc')
                ->limit(5)
                ->get();

            return view('mobile-service-management::dashboard.dashboard', compact(
                'workspace',
                'pendingRequest',
                'allRequest',
                'totalCompletedRequest',
                'totalIncome',
                'recentRequests'
            ));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }
}
