<?php

/*
    Created by Mohamed.
*/


namespace App\Http\Controllers\API;

use App\Models\Team;
use App\Models\User;
use App\Models\Order;
use App\Models\Review;
use App\Models\Contact;
use App\Models\StaticPage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use App\Http\Resources\SiteReviewResource;
use App\Http\Resources\TeamResource;
use App\Http\Resources\StaticPageResource;
use App\Models\SiteReview;

class StaticPageController extends Controller
{
    /**
     * Display a listing of static pages.
     */
    // public function index()
    // {
    //     $pages = \App\Models\StaticPage::all();
    //     return StaticPageResource::collection($pages);
    // }

    /**
     * Display a specific static page by key.
     */
    public function show($key)
    {
        $page = StaticPage::where('key', $key)->firstOrFail();
        return new StaticPageResource($page);
    }
    public function aboutUs()
    {
        $page = StaticPage::where('key', 'about-us')->firstOrFail();

        return response()->json([
            'message' => 'تم جلب البيانات بنجاح',
            'about-us' => new StaticPageResource($page),
            'statistics' => [
                'count-active-accounts' => User::where('is_active', 1)->orWhereNotNull('email_verified_at')->count(),
                'count-successful-orders' => Order::where('status_id', 1)->count(),
                'count-completed-orders' => Order::where('status_id', 3)->count(),
                'count-five-star-rating' => Review::where('rating', 5)->count(),
            ],
            'team' => TeamResource::collection(Team::all()),
            'site_reviews' => SiteReviewResource::collection(SiteReview::all()),


        ], 200);
    }

    public function contactUs(Request $request)
    {
        try {
            // Validate the request
            $validated = $request->validate([
                'email' => 'required|email|max:255',
                'subject' => 'required|string|max:255',
                'message' => 'required|string',
            ]);

            // Create the contact message
            Contact::create($validated);

            return response()->json([
                'status' => true,
                'message' => 'تم إرسال رسالتك بنجاح!',
            ], 200);

        } catch (\Illuminate\Validation\ValidationException $e) {
            // Handle validation errors explicitly
            return response()->json([
                'status' => false,
                'message' => 'خطأ في التحقق من البيانات.',
                'errors' => $e->errors(),
            ], 422);

        } catch (\Exception $e) {
            // Log and return generic error
            Log::error('Contact form submission failed: ' . $e->getMessage());

            return response()->json([
                'status' => false,
                'message' => 'حدث خطأ أثناء إرسال الرسالة. حاول مرة أخرى.',
            ], 500);
        }
    }

}