<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Service;
use Illuminate\Http\Request;
use App\Services\ImageService;

class ServiceController extends Controller
{
    public function index()
    {
        global $conn;
        $stmt = $conn->query("SELECT * FROM services ORDER BY created_at DESC");
        $services = array_map(fn($item) => (object)$item, $stmt->fetchAll());
        return view('admin.services.index', compact('services'));
    }

    public function create()
    {
        return view('admin.services.create');
    }

    public function store(Request $request)
    {
        global $conn;
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|unique:services,slug',
            'description' => 'nullable|string',
            'content' => 'nullable|string',
            'image' => 'nullable|image|max:2048',
            'image_alt' => 'nullable|string',
            'icon' => 'nullable|string|max:255',
            'benefits' => 'nullable|array',
            'features' => 'nullable|array',
            'price_starting_from' => 'nullable|string|max:255',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $featured_image = null;
        if ($request->hasFile('image')) {
            $path = ImageService::uploadAndOptimize($request->file('image'), 'services');
            $featured_image = asset('storage/' . $path);
        }

        $sql = "INSERT INTO services (title, slug, description, content, featured_image, image_alt, icon, benefits, features, price_starting_from, meta_title, meta_description, is_active, created_at, updated_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
        
        $stmt = $conn->prepare($sql);
        $stmt->execute([
            $validated['title'], $validated['slug'], $validated['description'] ?? '', $validated['content'] ?? '', 
            $featured_image, $validated['image_alt'] ?? '', $validated['icon'] ?? '', 
            isset($validated['benefits']) ? json_encode($validated['benefits']) : null, 
            isset($validated['features']) ? json_encode($validated['features']) : null, 
            $validated['price_starting_from'] ?? '', $validated['meta_title'] ?? '', $validated['meta_description'] ?? '', 
            $request->has('is_active') ? 1 : 0
        ]);

        return redirect()->route('admin.services.index')->with('success', 'Service created successfully.');
    }

    public function edit($id)
    {
        global $conn;
        $stmt = $conn->prepare("SELECT * FROM services WHERE id = ? LIMIT 1");
        $stmt->execute([$id]);
        $service = (object)$stmt->fetch();
        if (!$service || !isset($service->id)) abort(404);
        
        // Convert JSON strings back to arrays if needed for compatibility with old view code
        if (isset($service->benefits) && is_string($service->benefits)) $service->benefits = json_decode($service->benefits, true);
        if (isset($service->features) && is_string($service->features)) $service->features = json_decode($service->features, true);

        return view('admin.services.edit', compact('service'));
    }

    public function update(Request $request, $id)
    {
        global $conn;
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string', 
            'description' => 'nullable|string',
            'content' => 'nullable|string',
            'image' => 'nullable|image|max:2048',
            'image_alt' => 'nullable|string',
            'icon' => 'nullable|string|max:255',
            'benefits' => 'nullable|array',
            'features' => 'nullable|array',
            'price_starting_from' => 'nullable|string|max:255',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $sql = "UPDATE services SET title=?, slug=?, description=?, content=?, image_alt=?, icon=?, benefits=?, features=?, price_starting_from=?, meta_title=?, meta_description=?, is_active=?, updated_at=NOW()";
        $params = [
            $validated['title'], $validated['slug'], $validated['description'] ?? '', $validated['content'] ?? '', 
            $validated['image_alt'] ?? '', $validated['icon'] ?? '', 
            isset($validated['benefits']) ? json_encode($validated['benefits']) : null, 
            isset($validated['features']) ? json_encode($validated['features']) : null, 
            $validated['price_starting_from'] ?? '', $validated['meta_title'] ?? '', $validated['meta_description'] ?? '', 
            $request->has('is_active') ? 1 : 0
        ];

        if ($request->hasFile('image')) {
            $path = ImageService::uploadAndOptimize($request->file('image'), 'services');
            $sql .= ", featured_image=?";
            $params[] = asset('storage/' . $path);
        }

        $sql .= " WHERE id=?";
        $params[] = $id;

        $stmt = $conn->prepare($sql);
        $stmt->execute($params);

        return redirect()->route('admin.services.index')->with('success', 'Service updated successfully.');
    }

    public function destroy($id)
    {
        global $conn;
        $stmt = $conn->prepare("DELETE FROM services WHERE id = ?");
        $stmt->execute([$id]);
        return redirect()->route('admin.services.index')->with('success', 'Service deleted successfully.');
    }
}
