<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Certificate;
use App\Models\NewCertificate;
use App\Models\LastCertificate;
use App\Models\Product;
use App\Models\Role;
use App\Models\Webinar;
use App\Services\UserSerialGenerator;
use App\User;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function index(Request $request)
    {
        $data = [];

        $search = $request->get('search', null);

        if (!empty($search) and strlen($search) >= 3) {

            // Search for certificates by user serial number
            $certificates = collect();
            $user = UserSerialGenerator::getUserBySerial($search);
            
            if ($user) {
                $certificates = $user->getAllCertificates();
            } else {
                // Also search for certificates directly by serial number in all certificate tables
                $certificates = $this->searchCertificatesBySerial($search);
            }

            $webinars = Webinar::where('status', 'active')
                ->where('private', false)
                ->whereTranslationLike('title', "%$search%")
                ->with([
                    'teacher' => function ($query) {
                        $query->select('id', 'full_name', 'avatar');
                    },
                    'reviews'
                ])
                ->get();

            $products = Product::where('status', 'active')
                ->whereTranslationLike('title', "%$search%")
                ->with([
                    'creator' => function ($query) {
                        $query->select('id', 'full_name', 'avatar');
                    }
                ])
                ->get();

            $users = User::where('status', 'active')
                ->where('full_name', 'like', "%$search%")
                ->orWhere('email', 'like', "%$search%")
                ->orWhere('mobile', 'like', "%$search%")
                ->with([
                    'webinars' => function ($query) {
                        $query->where('status', 'active');
                        //dd(getBindedSQL($query));
                    }
                ])
                ->get();

            $teachers = $users->where('role_name', Role::$teacher);
            $organizations = $users->where('role_name', Role::$organization);

            $seoSettings = getSeoMetas('search');
            $pageTitle = !empty($seoSettings['title']) ? $seoSettings['title'] : trans('site.search_page_title');
            $pageDescription = !empty($seoSettings['description']) ? $seoSettings['description'] : trans('site.search_page_title');
            $pageRobot = getPageRobot('search');

            $data = [
                'pageTitle' => $pageTitle,
                'pageDescription' => $pageDescription,
                'pageRobot' => $pageRobot,
                'resultCount' => count($webinars) + count($teachers) + count($organizations) + count($products) + count($certificates),
                'webinars' => $webinars,
                'teachers' => $teachers,
                'organizations' => $organizations,
                'products' => $products,
                'certificates' => $certificates
            ];
        }

        return view(getTemplate() . '.pages.search', $data);
    }

    /**
     * Search certificates by serial number across all certificate tables
     */
    private function searchCertificatesBySerial($serialNumber)
    {
        $allCertificates = collect();

        // Search in old certificates table
        $oldCertificates = Certificate::where('serial_number', $serialNumber)
            ->with(['quiz.webinar', 'webinar', 'student'])
            ->get();
        
        foreach ($oldCertificates as $cert) {
            $cert->certificate_type = 'old';
            $allCertificates->push($cert);
        }

        // Search in new certificates table
        $newCertificates = NewCertificate::where('serial_number', $serialNumber)
            ->with('template')
            ->get();
        
        foreach ($newCertificates as $cert) {
            $cert->certificate_type = 'new';
            $allCertificates->push($cert);
        }

        // Search in last certificates table (if it has serial number field)
        // Note: LastCertificate might not have serial_number field, so we'll search by user
        $users = User::where('serial_number', $serialNumber)->get();
        foreach ($users as $user) {
            $lastCertificates = LastCertificate::where('user_id', $user->id)->get();
            foreach ($lastCertificates as $cert) {
                $cert->certificate_type = 'last';
                $allCertificates->push($cert);
            }
        }

        return $allCertificates;
    }
}
