<?php
namespace App\Http\Controllers\Admin;

use App\Helpers\ApiResponse;
use App\Helpers\CacheHelper;
use App\Http\Controllers\Controller;
use App\Models\FormSubmission;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;



class FormSubmissionController extends Controller
{
    /**
     * Get all Franchisee Forms count for super admin
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getFranchiseeForms(Request $request)
    {
        $auth = Auth::user();
        if (!$auth) {
            return ApiResponse::error("Unauthorized", Response::HTTP_UNAUTHORIZED);
        }
        $perPage = $request->get('per_page', 15);
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order');
        $sortOrder = $sortOrder == "1" ? 'asc' : ($sortOrder == "-1" ? 'desc' : 'asc');
        $search = $request->get('search', '');
        $cacheKey = 'submission_forms' . md5(json_encode([
            'search' => $search,
            'sort_by' => $sortBy,
            'sort_order' => $sortOrder,
            'per_page' => $perPage,
            'page' => $request->get('page', 1)
        ]));
        try {
            // 🔹 Remember for 60 minutes (3600s)
            $submissions = CacheHelper::rememberByTag('submission_forms', $cacheKey, function () use ($auth, $sortBy, $sortOrder, $search, $perPage) {

                $query = FormSubmission::with(['franchisee:id,name,email'])
                    ->select(
                        'franchisee_id',
                        DB::raw('COUNT(DISTINCT form_id) as total_forms'),
                        DB::raw('MAX(created_at) as last_submission')
                    )
                    ->groupBy('franchisee_id');

                /**
                 * Optional search: franchisee name or email
                 */
                if (!empty($search)) {
                    $query->whereHas('franchisee', function ($q) use ($search) {
                        $q->where('name', 'ILIKE', "%{$search}%")
                            ->orWhere('email', 'ILIKE', "%{$search}%");
                    });
                }

                /**
                 * Optional sorting
                 */
                $sortBy = in_array($sortBy, ['total_forms', 'last_submission']) ? $sortBy : 'last_submission';
                $sortOrder = $sortOrder === 'asc' ? 'asc' : 'desc';

                return $query
                    ->orderBy($sortBy, $sortOrder)
                    ->paginate($perPage);

            });
            return ApiResponse::success(
                $submissions,
                'Form submissions aggregated by franchisee'
            );
        } catch (\Throwable $e) {
            return ApiResponse::exception($e);
        }
    }

    /**
     * Get 0Submited form data by Franchisee Id
     * @param mixed $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function getFranchiseeFormsById($id)
    {
        try {
            $submissions = FormSubmission::with([
                'form:id,name,pages,language'
            ])
                ->where('franchisee_id', $id)
                ->latest()
                ->get();

            // Transform for response
            $result = $submissions->map(function ($submission) {
                $form = $submission->form;

                return [
                    'submission_id' => $submission->id,
                    'form_id' => $form?->id,
                    'form_name' => $form?->name,
                    'pages' => $submission->page,
                    'language' => $form?->language,
                    'submitted_at' => $submission->created_at,
                    'submission_data' => $submission->submission_data,
                ];
            });

            return ApiResponse::success(
                $result,
                'Franchisee submissions with form data'
            );

        } catch (\Throwable $e) {
            return ApiResponse::exception($e);
        }
    }

}
