<?php

namespace App\Http\Controllers;

use Intervention\Image\Laravel\Facades\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use App\Traits\TracksManualEdits;  // ← ADDED: Manual edit tracking

class CategoryController extends Controller
{
    use TracksManualEdits;  // ← ADDED: Enable manual edit tracking
    /**
     * Display category management page
     */
    public function index()
    {
        $categories = DB::table('categories')
            ->leftJoin(
                DB::raw('(SELECT category_id, COUNT(*) as product_count FROM products GROUP BY category_id) as p'),
                'categories.id',
                '=',
                'p.category_id'
            )
            ->select('categories.*', DB::raw('COALESCE(p.product_count, 0) as product_count'))
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        return view('account.categories.index', compact('categories'));
    }

    /**
     * Store new category
     */
   public function store(Request $request)
{
    try {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'brand_code' => 'nullable|string|max:100',
            'category_type' => 'required|in:game,ewallet,pulsa,voucher,streaming,subscription',
            'description' => 'nullable|string',
            'icon' => 'nullable|string|max:100',
            'sort_order' => 'nullable|integer',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'is_popular' => 'nullable',
            'input_type' => 'required|string|in:user-id,user-id-zone,email,phone,username,voucher',
        ]);

        $imagePath = null;

        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $fileName = 'cat-' . time() . '-' . Str::random(10) . '.webp';
            $imagePath = 'categories/' . $fileName;

            if (!Storage::disk('public')->exists('categories')) {
                Storage::disk('public')->makeDirectory('categories');
            }

            $manager = new ImageManager(new Driver());
            $image = $manager->read($file);
            $image->scale(width: 400);
            $encoded = $image->toWebp(75);
            Storage::disk('public')->put($imagePath, (string) $encoded);
        }

        // ✅ CONVERT is_popular PROPERLY
        $isPopular = 0;
        if ($request->has('is_popular')) {
            $val = $request->input('is_popular');
            $isPopular = in_array($val, ['1', 1, true, 'true']) ? 1 : 0;
        }

        $data = [
            'name' => $validated['name'],
            'slug' => Str::slug($validated['name']),
            'brand_code' => $validated['brand_code'] ?? null,
            'category_type' => $validated['category_type'],
            'description' => $validated['description'] ?? null,
            'icon' => $validated['icon'] ?? 'fas fa-tag',
            'sort_order' => $validated['sort_order'] ?? 0,
            'image' => $imagePath,
            'input_type' => $validated['input_type'],
            'is_popular' => $isPopular,
            'is_active' => true,
            'manual_image' => $imagePath ? true : false,
            'manual_description' => !empty($validated['description']),
            'manual_name' => false,
            'created_at' => now(),
            'updated_at' => now(),
        ];

        DB::table('categories')->insert($data);

        return response()->json([
            'success' => true,
            'message' => 'Category created successfully!'
        ]);

    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Validation failed',
            'errors' => $e->errors()
        ], 422);
    } catch (\Exception $e) {
        \Log::error('Store error', [
            'message' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);
        return response()->json([
            'success' => false,
            'message' => 'Server error: ' . $e->getMessage()
        ], 500);
    }
}

    /**
     * Update category
     */
    public function update(Request $request, $id)
{
    try {
        $category = DB::table('categories')->where('id', $id)->first();

        if (!$category) {
            return response()->json(['success' => false, 'message' => 'Category not found!'], 404);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'brand_code' => 'nullable|string|max:100',
            'category_type' => 'required|in:game,ewallet,pulsa,voucher,streaming,subscription',
            'description' => 'nullable|string',
            'icon' => 'nullable|string|max:100',
            'sort_order' => 'nullable|integer',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'is_popular' => 'nullable',
            'input_type' => 'required|string|in:user-id,user-id-zone,email,phone,username,voucher',
        ]);

        $imagePath = $category->image;

        if ($request->hasFile('image')) {
            // Hapus gambar lama
            if ($category->image) {
                Storage::disk('public')->delete($category->image);
            }

            // Proses gambar baru
            $file = $request->file('image');
            $fileName = 'cat-' . time() . '-' . Str::random(10) . '.webp';
            $imagePath = 'categories/' . $fileName;

            $manager = new ImageManager(new Driver());
            $image = $manager->read($file);
            $image->scale(width: 400);
            $encoded = $image->toWebp(75);
            Storage::disk('public')->put($imagePath, (string) $encoded);
        }

        // ✅ CONVERT is_popular PROPERLY
        $isPopular = 0;
        if ($request->has('is_popular')) {
            $val = $request->input('is_popular');
            // Convert string "1" atau "0" atau true/false jadi integer
            $isPopular = in_array($val, ['1', 1, true, 'true']) ? 1 : 0;
        }

        $data = [
            'name' => $validated['name'],
            'slug' => Str::slug($validated['name']),
            'brand_code' => $validated['brand_code'] ?? null,
            'category_type' => $validated['category_type'],
            'description' => $validated['description'] ?? null,
            'icon' => $validated['icon'] ?? $category->icon,
            'sort_order' => $validated['sort_order'] ?? 0,
            'image' => $imagePath,
            'input_type' => $validated['input_type'],
            'is_popular' => $isPopular, // ✅ USE CONVERTED VALUE
            'updated_at' => now(),
        ];

        // ============================================
        // 🔥 TRACK MANUAL EDITS - Protect from sync!
        // ============================================
        $manualFields = [];
        
        // Track if image was uploaded
        if ($request->hasFile('image')) {
            $data['manual_image'] = true;
            $manualFields[] = 'image';
        }
        
        // Track if description changed
        if ($request->has('description') && $validated['description'] !== $category->description) {
            $data['manual_description'] = true;
            $manualFields[] = 'description';
        }
        
        // Track if name changed
        if ($validated['name'] !== $category->name) {
            $data['manual_name'] = true;
            $manualFields[] = 'name';
        }

        DB::table('categories')->where('id', $id)->update($data);

        return response()->json([
            'success' => true,
            'message' => 'Category updated successfully!' . 
                         (count($manualFields) > 0 ? ' 🔒 Protected: ' . implode(', ', $manualFields) : ''),
            'protected_fields' => $manualFields
        ]);

    } catch (\Illuminate\Validation\ValidationException $e) {
        \Log::error('Validation error', ['errors' => $e->errors()]);
        return response()->json([
            'success' => false,
            'message' => 'Validation failed',
            'errors' => $e->errors()
        ], 422);
    } catch (\Exception $e) {
        \Log::error('Update error', [
            'message' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);
        return response()->json([
            'success' => false,
            'message' => 'Server error: ' . $e->getMessage()
        ], 500);
    }
}

    /**
     * Delete category
     */
    public function destroy($id)
    {
        $category = DB::table('categories')->where('id', $id)->first();

        if (!$category) {
            return response()->json([
                'success' => false,
                'message' => 'Category not found!'
            ], 404);
        }

        $productCount = DB::table('products')->where('category_id', $id)->count();
        
        if ($productCount > 0) {
            return response()->json([
                'success' => false,
                'message' => "Cannot delete category with {$productCount} products!"
            ], 400);
        }

        if ($category->image) {
            Storage::disk('public')->delete($category->image);
        }

        DB::table('categories')->where('id', $id)->delete();

        return response()->json([
            'success' => true,
            'message' => 'Category deleted successfully!'
        ]);
    }

    /**
     * Get single category (for edit modal)
     */
    public function show($id)
    {
        $category = DB::table('categories')->where('id', $id)->first();

        if (!$category) {
            return response()->json([
                'success' => false,
                'message' => 'Category not found!'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $category
        ]);
    }

    /**
     * Toggle category status
     */
    public function toggleStatus($id)
    {
        $category = DB::table('categories')->where('id', $id)->first();

        if (!$category) {
            return response()->json([
                'success' => false,
                'message' => 'Category not found!'
            ], 404);
        }

        $newStatus = !$category->is_active;

        DB::table('categories')->where('id', $id)->update([
            'is_active' => $newStatus,
            'updated_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Category status updated!',
            'status' => $newStatus
        ]);
    }

    public function updateBanner(Request $request)
    {
        $request->validate([
            'banner' => 'required|image|mimes:jpg,jpeg,png,webp|max:3072',
        ]);

        $file = $request->file('banner');
        $filename = 'slider-' . time() . '-' . uniqid() . '.webp';
        $targetPath = public_path('images/banner');

        if (!file_exists($targetPath)) {
            mkdir($targetPath, 0755, true);
        }

        $manager = new ImageManager(new Driver());
        $image = $manager->read($file);
        $image->scale(width: 1200); 
        $image->toWebp(75)->save($targetPath . '/' . $filename);

        DB::table('sliders')->insert([
            'image' => 'images/banner/' . $filename,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return back()->with('success', 'Banner berhasil ditambahkan & dioptimasi ke WebP!');
    }

    public function deleteBanner($id)
    {
        $slide = DB::table('sliders')->where('id', $id)->first();
        
        if ($slide) {
            $filePath = public_path($slide->image);
            if (file_exists($filePath)) {
                unlink($filePath);
            }

            DB::table('sliders')->where('id', $id)->delete();
            return back()->with('success', 'Banner berhasil dihapus!');
        }

        return back()->with('error', 'Banner tidak ditemukan!');
    }
    private function getConfig($category)
{
    // Genshin Impact
    if ($category->slug === 'genshin-impact') {
        return [
            'id_label' => 'UID',
            'id_placeholder' => 'Contoh: 800000000',
            'id_icon' => 'fa-id-card',
            'show_zone' => true,
            'zone_type' => 'dropdown',
            'zone_label' => 'Server',
            'zone_placeholder' => 'Pilih Server',
            'zone_icon' => 'fa-server',
            'zone_options' => [
                'os_asia' => 'Asia',
                'os_usa' => 'America',
                'os_euro' => 'Europe',
                'os_cht' => 'TW, HK, MO'
            ],
            'is_voucher' => false,
        ];
    }
    
    // PUBG
    if ($category->slug === 'pubg-mobile') {
        return [
            'id_label' => 'User ID',
            'id_placeholder' => 'Contoh: 5123456789',
            'id_icon' => 'fa-id-card',
            'show_zone' => false,
            'is_voucher' => false,
        ];
    }
    
    // Default
    return [
        'id_label' => 'User ID',
        'id_placeholder' => 'Masukkan User ID',
        'id_icon' => 'fa-id-card',
        'show_zone' => false,
        'is_voucher' => false,
    ];
}
}