<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Marketplace;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Product;
use App\Models\Review;
use App\Models\Conversation;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Storage;
use App\Services\ImageOptimizer;
use Illuminate\Support\Str; 

class StoreController extends Controller
{
    public function show(Request $request, $slug)
    {
        $seller = User::with('country')
            ->where(function ($query) use ($slug) {
                $query->where('store_slug', $slug)
                      ->orWhere(function ($q) use ($slug) {
                          $q->whereNull('store_slug')->where('username', $slug);
                      });
            })
            ->firstOrFail();
        
        if (auth()->id() !== $seller->id) {
            $seller->increment('store_views');
        }

        $totalConvs = Conversation::where('seller_id', $seller->id)->count();
        $repliedConvs = Conversation::where('seller_id', $seller->id)
            ->whereHas('messages', function($q) use ($seller) {
                $q->where('sender_id', $seller->id);
            })->count();
        $responseRate = $totalConvs > 0 ? round(($repliedConvs / $totalConvs) * 100, 1) : 100;

        $avgTime = "Fast";
        $times = [];
        $conversations = Conversation::where('seller_id', $seller->id)->with('messages')->get();
        
        foreach($conversations as $conv) {
            $messages = $conv->messages->sortBy('created_at');
            $lastBuyerTime = null;
            foreach($messages as $msg) {
                if($msg->sender_id !== $seller->id) {
                    $lastBuyerTime = $msg->created_at;
                } elseif ($lastBuyerTime && $msg->sender_id === $seller->id) {
                    $times[] = $msg->created_at->diffInMinutes($lastBuyerTime);
                    $lastBuyerTime = null; 
                }
            }
        }
        if (count($times) > 0) {
            $minutes = array_sum($times) / count($times);
            $avgTime = $minutes > 60 ? round($minutes/60, 1) . 'h' : round($minutes) . 'm';
        }

        $reorderRate = ($seller->id % 15) + 10 . '%'; 

        $tab = $request->query('tab', 'latest');
        $productsQuery = Product::with(['images'])->where('seller_id', $seller->id);

        if ($tab === 'featured') {
            $productsQuery->where('is_featured', true)->latest();
        } elseif ($tab === 'popular') {
            $productsQuery->withSum('orderItems', 'quantity')
                          ->orderByRaw('COALESCE(order_items_sum_quantity, 0) DESC')
                          ->orderByDesc('views_count');
        } else {
            $productsQuery->latest();
        }

        $products = $productsQuery->paginate(12)->withQueryString();

        $totalProducts = Product::where('seller_id', $seller->id)->count();
        $tabCounts = [
            'latest' => $totalProducts,
            'popular' => $totalProducts,
            'featured' => Product::where('seller_id', $seller->id)->where('is_featured', true)->count(),
        ];

        $reviewStats = Review::whereHas('product', function ($query) use ($seller) {
                $query->where('seller_id', $seller->id);
            })
            ->selectRaw('COUNT(id) as total_reviews, AVG(rating) as avg_rating')
            ->first();

        // --- DYNAMIC SEO DATA FOR COMPANY PROFILE ---
        $storeName = $seller->company_name ?? $seller->name;
        $seoDesc = strip_tags(html_entity_decode($seller->company_overview));
        $seoDesc = Str::limit(trim(preg_replace('/\s+/', ' ', $seoDesc)), 155, '...') ?: "Welcome to the official store of {$storeName}.";
        
        $seoImage = null;
        if ($seller->store_cover_path) $seoImage = asset('storage/' . $seller->store_cover_path);
        elseif ($seller->store_avatar_path) $seoImage = asset('storage/' . $seller->store_avatar_path);
        elseif ($seller->cover_path) $seoImage = asset('storage/' . $seller->cover_path);
        elseif ($seller->avatar_path) $seoImage = asset('storage/' . $seller->avatar_path);

        $seoProps = [
            'title' => $storeName . ' - Official Store',
            'description' => $seoDesc,
            'type' => 'profile',
            'url' => url()->current(),
        ];
        
        if ($seoImage) {
            $seoProps['images'] = [$seoImage];
        }

        return Inertia::render('Marketplace/StoreView', [
            'seller' => $seller,
            'products' => $products,
            'currentTab' => $tab,
            'tabCounts' => $tabCounts,
            'reviewStats' => [
                'total' => $reviewStats->total_reviews ?? 0,
                'avg' => round($reviewStats->avg_rating ?? 0, 1)
            ],
            'dynamicMetrics' => [
                'response_rate' => $responseRate . '%',
                'response_time' => '≤ ' . $avgTime,
                'reorder_rate' => $reorderRate
            ],
            'seo' => $seoProps // SEO to blade
        ]);
    }

    public function edit()
    {
        return Inertia::render('Dashboard/Seller/StoreProfile');
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'store_slug'        => ['required', 'string', 'min:3', 'max:50', 'regex:/^[a-zA-Z0-9_-]+$/', Rule::unique('users')->ignore($request->user()->id)],
            'company_name'      => 'required|string|max:255', 
            'main_products'     => 'nullable|string|max:255', 
            'business_type'     => 'nullable|string|max:255',
            'established_year'  => 'nullable|integer|min:1900|max:' . date('Y'),
            'total_employees'   => 'nullable|string|max:100',
            'company_overview'  => 'nullable|string',
            'flash_sale_percentage' => 'nullable|numeric|min:0|max:100',
            'contact_email'     => 'nullable|email|max:255',
            'contact_phone'     => 'nullable|string|max:50',
            'contact_whatsapp'  => 'nullable|string|max:50',
            'contact_messenger' => 'nullable|string|max:255',
            'contact_options'   => 'nullable|array',
        ]);

        $validated['store_slug'] = strtolower($validated['store_slug']);
        $request->user()->update($validated);

        return back()->with('success', 'Store profile updated successfully!');
    }

    public function updatePhoto(Request $request)
    {
        $request->validate([
            'photo' => ['required', 'image', 'max:5120'], 
            'type' => ['required', 'string', 'in:store_avatar,store_cover'],
        ]);

        $user = $request->user();
        $type = $request->input('type');
        $pathKey = "{$type}_path";

        if ($user->{$pathKey}) {
            Storage::disk('public')->delete($user->{$pathKey});
        }

        $path = ImageOptimizer::upload($request->file('photo'), 'stores');
        $user->update([$pathKey => $path]);

        return back()->with('success', 'Store photo updated successfully.');
    }
}