<?php

namespace App\Http\Controllers;

use App\Models\Collection;
use Illuminate\Http\Request;

class CollectionController extends Controller
{
    public function index()
    {
        $collections = Collection::orderBy('sort_order', 'asc')->get();
        return response()->json($collections);
    }

    public function products(string $slug)
    {
        $collection = Collection::where('slug', $slug)->firstOrFail();

        // Sort: price ASC, then sort_color (black, white, pink) ASC
        // SQLite does not support FIELD(), so we use a CASE statement which is database-agnostic
        $products = $collection->products()
            ->where('is_active', true)
            ->with(['images', 'variants'])
            ->orderBy('base_price', 'asc')
            ->orderByRaw("CASE sort_color WHEN 'black' THEN 1 WHEN 'white' THEN 2 WHEN 'pink' THEN 3 ELSE 4 END ASC")
            ->get();

        return response()->json([
            'collection' => $collection,
            'products' => $products
        ]);
    }

    public function settings()
    {
        $keys = [
            'whatsapp_number',
            'phone_number',
            'instagram_url',
            'tiktok_url',
            'facebook_url',
            'twitter_url',
            'mpesa_till_number',
            'mpesa_env',
            'delivery_fee',
            'delivery_note',
            'terms_and_conditions',
            'footer_tagline',
            'announcements',
            'delivery_rates',
            'payment_methods'
        ];

        $settings = [];
        foreach ($keys as $key) {
            $settings[$key] = \App\Models\SiteSetting::getValue($key, '');
        }

        return response()->json($settings);
    }
}
