<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class BilinggoApiController extends Controller
{
    // ── Helper Authentication Methods ─────────────────────────────────────────

    private function getBearerToken(Request $request)
    {
        $h = $request->header('Authorization') ?: $request->header('X-Auth-Token');
        if ($h && str_starts_with($h, 'Bearer ')) {
            return substr($h, 7);
        }
        return $request->input('token') ?: '';
    }

    private function requireAuth(Request $request)
    {
        $token = $this->getBearerToken($request);
        if (!$token) {
            abort(response()->json(['success' => false, 'message' => 'Token otentikasi diperlukan. Silakan login.'], 401));
        }
        $session = \App\Models\CustomerSession::where('token', $token)
            ->where('expires_at', '>', now())
            ->first();
        if (!$session) {
            abort(response()->json(['success' => false, 'message' => 'Sesi telah kedaluwarsa. Silakan login kembali.'], 401));
        }
        $cust = \App\Models\Customer::find($session->customer_id);
        if (!$cust) {
            abort(response()->json(['success' => false, 'message' => 'Pelanggan tidak ditemukan.'], 404));
        }
        return $cust;
    }

    private function requireAdmin(Request $request)
    {
        $token = $this->getBearerToken($request);
        if (!$token) {
            abort(response()->json(['success' => false, 'message' => 'Token admin diperlukan. Silakan login.'], 401));
        }
        $session = \App\Models\CustomerSession::where('token', $token)
            ->where('customer_id', 0)
            ->where('expires_at', '>', now())
            ->first();
        if (!$session) {
            abort(response()->json(['success' => false, 'message' => 'Akses ditolak. Sesi admin tidak valid atau kedaluwarsa.'], 403));
        }
    }

    private function generateToken(int $customerId): string
    {
        $token = bin2hex(random_bytes(32));
        \App\Models\CustomerSession::create([
            'customer_id' => $customerId,
            'token' => $token,
            'expires_at' => now()->addDays(30),
        ]);
        return $token;
    }

    private function formatCustomer($c): array
    {
        if (!$c) return [];
        return [
            'id' => (int)$c->id,
            'name' => $c->name,
            'email' => $c->email,
            'phone' => $c->phone ?? '',
            'isActive' => (bool)$c->is_active,
            'createdAt' => $c->created_at ? $c->created_at->format('Y-m-d H:i:s') : null,
            'lastLogin' => $c->last_login ? (\Carbon\Carbon::parse($c->last_login)->format('Y-m-d H:i:s')) : null,
            'initials' => strtoupper(substr($c->name, 0, 1)),
        ];
    }

    private function formatProduct($p): array
    {
        if (!$p) return [];
        return [
            'id'            => (int)$p->id,
            'name'          => $p->name,
            'desc'          => $p->description,
            'price'         => $p->price,
            'promoPrice'    => $p->promo_price,
            'image'         => $p->image,
            'category'      => $p->category,
            'shopeeUrl'     => $p->shopee_url,
            'tokopediaUrl'  => $p->tokopedia_url,
            'vaDetails'     => $p->va_details,
            'stock'         => (int)$p->stock,
            'isActive'      => (bool)$p->is_active,
            'sortOrder'     => (int)$p->sort_order,
            'createdAt'     => $p->created_at ? $p->created_at->format('Y-m-d H:i:s') : null,
        ];
    }

    private function formatSlide($s): array
    {
        if (!$s) return [];
        $outcomes = $s->outcomes ? explode('|', $s->outcomes) : [];
        return [
            'id'           => (int)$s->id,
            'type'         => $s->type,
            'techText'     => $s->tech_text,
            'title'        => $s->title,
            'subtitle'     => $s->subtitle,
            'tagline'      => $s->tagline,
            'outcomes'     => $outcomes,
            'date'         => $s->event_date,
            'oldPrice'     => $s->old_price,
            'newPrice'     => $s->new_price,
            'bonus'        => $s->bonus,
            'btnText'      => $s->btn_text,
            'image'        => $s->image,
            'speakerName'  => $s->speaker_name,
            'speakerTitle1'=> $s->speaker_title1,
            'speakerTitle2'=> $s->speaker_title2,
            'speakerImage' => $s->speaker_image,
            'isActive'     => (bool)$s->is_active,
            'sortOrder'    => (int)$s->sort_order,
            'createdAt'    => $s->created_at ? $s->created_at->format('Y-m-d H:i:s') : null,
        ];
    }

    private function formatSession($s): array
    {
        if (!$s) return [];
        return [
            'id'        => (int)$s->id,
            'date'      => $s->event_date,
            'name'      => $s->name,
            'desc'      => $s->description,
            'bgColor'   => $s->bg_color,
            'tall'      => (bool)$s->is_tall,
            'sortOrder' => (int)$s->sort_order,
        ];
    }

    // ── AUTH ENDPOINT ─────────────────────────────────────────────────────────

    public function auth(Request $request)
    {
        $action = $request->query('action') ?: $request->input('action');
        
        switch ($action) {
            case 'register':
                if (!$request->isMethod('post')) {
                    return response()->json(['success' => false, 'message' => 'POST required'], 405);
                }
                $name = trim($request->input('name') ?? '');
                $email = trim($request->input('email') ?? '');
                $phone = trim($request->input('phone') ?? '');
                $password = $request->input('password') ?? '';
                $confirm = $request->input('confirm_password') ?? $password;

                $errors = [];
                if (!$name) $errors[] = 'Nama lengkap wajib diisi.';
                if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Format email tidak valid.';
                if (strlen($password) < 6) $errors[] = 'Password minimal 6 karakter.';
                if ($password !== $confirm) $errors[] = 'Konfirmasi password tidak cocok.';

                if ($errors) {
                    return response()->json(['success' => false, 'errors' => $errors, 'message' => implode(' ', $errors)], 422);
                }

                $emailLower = strtolower($email);
                if (\App\Models\Customer::where('email', $emailLower)->exists()) {
                    return response()->json(['success' => false, 'message' => 'Email sudah terdaftar. Silakan login.'], 409);
                }

                $hash = bcrypt($password);
                $customer = \App\Models\Customer::create([
                    'name' => $name,
                    'email' => $emailLower,
                    'phone' => $phone,
                    'password_hash' => $hash,
                    'is_active' => 1,
                ]);

                $token = $this->generateToken($customer->id);
                
                return response()->json([
                    'success' => true,
                    'message' => 'Registrasi berhasil! Selamat datang di BilînGo.',
                    'token' => $token,
                    'customer' => $this->formatCustomer($customer)
                ], 201);

            case 'login':
                if (!$request->isMethod('post')) {
                    return response()->json(['success' => false, 'message' => 'POST required'], 405);
                }
                $email = strtolower(trim($request->input('email') ?? ''));
                $pass = $request->input('password') ?? '';

                if (!$email || !$pass) {
                    return response()->json(['success' => false, 'message' => 'Email dan password wajib diisi.'], 422);
                }

                $customer = \App\Models\Customer::where('email', $email)->where('is_active', 1)->first();

                if (!$customer || !Hash::check($pass, $customer->password_hash)) {
                    return response()->json(['success' => false, 'message' => 'Email atau password salah.'], 401);
                }

                // Revoke expired sessions
                \App\Models\CustomerSession::where('customer_id', $customer->id)->where('expires_at', '<', now())->delete();

                $token = $this->generateToken($customer->id);
                $customer->update(['last_login' => now()]);

                return response()->json([
                    'success' => true,
                    'message' => 'Login berhasil!',
                    'token' => $token,
                    'customer' => $this->formatCustomer($customer)
                ]);

            case 'logout':
                $token = $this->getBearerToken($request);
                if ($token) {
                    \App\Models\CustomerSession::where('token', $token)->delete();
                }
                return response()->json(['success' => true, 'message' => 'Logout berhasil.']);

            case 'me':
                $customer = $this->requireAuth($request);
                return response()->json(['success' => true, 'customer' => $this->formatCustomer($customer)]);

            case 'profile':
                if (!$request->isMethod('put') && !$request->isMethod('post')) {
                    return response()->json(['success' => false, 'message' => 'PUT required'], 405);
                }
                $customer = $this->requireAuth($request);
                $name = trim($request->input('name') ?? $customer->name);
                $phone = trim($request->input('phone') ?? $customer->phone);
                
                $customer->update(['name' => $name, 'phone' => $phone]);

                if ($request->filled('new_password')) {
                    if (!Hash::check($request->input('current_password') ?? '', $customer->password_hash)) {
                        return response()->json(['success' => false, 'message' => 'Password lama salah.'], 401);
                    }
                    if (strlen($request->input('new_password')) < 6) {
                        return response()->json(['success' => false, 'message' => 'Password baru minimal 6 karakter.'], 422);
                    }
                    $customer->update(['password_hash' => bcrypt($request->input('new_password'))]);
                }

                return response()->json([
                    'success' => true,
                    'message' => 'Profil berhasil diperbarui.',
                    'customer' => $this->formatCustomer($customer)
                ]);

            case 'verify':
                $token = $this->getBearerToken($request);
                if (!$token) {
                    return response()->json(['success' => false, 'message' => 'Token tidak ada.'], 401);
                }
                $session = \App\Models\CustomerSession::where('token', $token)->where('expires_at', '>', now())->first();
                if (!$session) {
                    return response()->json(['success' => false, 'message' => 'Token tidak valid atau sudah kedaluwarsa.'], 401);
                }
                $cust = \App\Models\Customer::find($session->customer_id);
                return response()->json(['success' => true, 'customer' => $this->formatCustomer($cust)]);

            case 'admin_login':
                if (!$request->isMethod('post')) {
                    return response()->json(['success' => false, 'message' => 'POST required'], 405);
                }
                $user = trim($request->input('username') ?? '');
                $pass = $request->input('password') ?? '';

                if (!$user || !$pass) {
                    return response()->json(['success' => false, 'message' => 'Username dan password wajib diisi.'], 422);
                }

                $dbUser = \App\Models\Setting::where('key_name', 'admin_username')->value('value') ?: 'admin';
                $dbPass = \App\Models\Setting::where('key_name', 'admin_password')->value('value') ?: 'admin';

                if ($user !== $dbUser || $pass !== $dbPass) {
                    return response()->json(['success' => false, 'message' => 'Username atau password admin salah.'], 401);
                }

                $token = $this->generateToken(0);
                return response()->json(['success' => true, 'message' => 'Login admin berhasil!', 'token' => $token]);

            case 'list':
                $this->requireAdmin($request);
                $customers = \App\Models\Customer::orderBy('id', 'desc')->get()->map(function($c) {
                    return $this->formatCustomer($c);
                });
                return response()->json(['success' => true, 'customers' => $customers]);

            case 'toggle_status':
                if (!$request->isMethod('post') && !$request->isMethod('put')) {
                    return response()->json(['success' => false, 'message' => 'POST/PUT required'], 405);
                }
                $this->requireAdmin($request);
                $id = (int)($request->input('id') ?: $request->query('id') ?: 0);
                if (!$id) {
                    return response()->json(['success' => false, 'message' => 'ID pelanggan wajib ada.'], 400);
                }

                $customer = \App\Models\Customer::find($id);
                if (!$customer) {
                    return response()->json(['success' => false, 'message' => 'Pelanggan tidak ditemukan.'], 404);
                }

                $newStatus = $customer->is_active ? 0 : 1;
                $customer->update(['is_active' => $newStatus]);

                if ($newStatus === 0) {
                    \App\Models\CustomerSession::where('customer_id', $id)->delete();
                }

                return response()->json(['success' => true, 'message' => 'Status pelanggan berhasil diperbarui.', 'isActive' => $newStatus]);

            case 'update_customer':
                if (!$request->isMethod('post') && !$request->isMethod('put')) {
                    return response()->json(['success' => false, 'message' => 'POST/PUT required'], 405);
                }
                $this->requireAdmin($request);
                $id = (int)($request->input('id') ?: $request->query('id') ?: 0);
                if (!$id) {
                    return response()->json(['success' => false, 'message' => 'ID pelanggan wajib ada.'], 400);
                }

                $customer = \App\Models\Customer::find($id);
                if (!$customer) {
                    return response()->json(['success' => false, 'message' => 'Pelanggan tidak ditemukan.'], 404);
                }

                $name = trim($request->input('name') ?? '');
                $email = strtolower(trim($request->input('email') ?? ''));
                $phone = trim($request->input('phone') ?? '');
                $password = $request->input('password') ?? '';

                if (!$name) {
                    return response()->json(['success' => false, 'message' => 'Nama lengkap wajib diisi.'], 422);
                }
                if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    return response()->json(['success' => false, 'message' => 'Format email tidak valid.'], 422);
                }

                if (\App\Models\Customer::where('email', $email)->where('id', '!=', $id)->exists()) {
                    return response()->json(['success' => false, 'message' => 'Email sudah digunakan oleh pelanggan lain.'], 409);
                }

                $customer->update(['name' => $name, 'email' => $email, 'phone' => $phone]);

                if ($password !== '') {
                    if (strlen($password) < 6) {
                        return response()->json(['success' => false, 'message' => 'Password minimal 6 karakter.'], 422);
                    }
                    $customer->update(['password_hash' => bcrypt($password)]);
                    \App\Models\CustomerSession::where('customer_id', $id)->delete();
                }

                return response()->json([
                    'success' => true,
                    'message' => 'Data pelanggan berhasil diperbarui.',
                    'customer' => $this->formatCustomer($customer)
                ]);

            case 'delete_customer':
                if (!$request->isMethod('delete') && !$request->isMethod('post')) {
                    return response()->json(['success' => false, 'message' => 'DELETE/POST required'], 405);
                }
                $this->requireAdmin($request);
                $id = (int)($request->query('id') ?: $request->input('id') ?: 0);
                if (!$id) {
                    return response()->json(['success' => false, 'message' => 'ID pelanggan wajib ada.'], 400);
                }

                $customer = \App\Models\Customer::find($id);
                if (!$customer) {
                    return response()->json(['success' => false, 'message' => 'Pelanggan tidak ditemukan.'], 404);
                }

                \App\Models\CustomerSession::where('customer_id', $id)->delete();
                $customer->delete();

                return response()->json(['success' => true, 'message' => 'Pelanggan berhasil dihapus.']);

            default:
                return response()->json(['success' => false, 'message' => 'Action tidak dikenal.'], 400);
        }
    }

    // ── PRODUCTS ENDPOINT ─────────────────────────────────────────────────────

    public function products(Request $request)
    {
        $action = $request->query('action');
        $id = $request->query('id') ?: $request->input('id');

        if ($request->isMethod('get')) {
            if ($action === 'stats') {
                $this->requireAdmin($request);
                $stats = [
                    'products'      => (int)\App\Models\Product::where('is_active', 1)->count(),
                    'orders'        => (int)\App\Models\Order::count(),
                    'registrations' => (int)\App\Models\Registration::count(),
                    'slides'        => (int)\App\Models\Slide::where('is_active', 1)->count(),
                    'sessions'      => (int)\App\Models\Session::count(),
                    'news'          => (int)\App\Models\News::count(),
                    'revenue'       => (int)\App\Models\Order::where('status', 'completed')->sum('total_price'),
                    'pending_orders'=> (int)\App\Models\Order::where('status', 'pending')->count(),
                ];
                return response()->json(['success' => true, 'data' => $stats]);
            }
            if ($id) {
                $p = \App\Models\Product::find($id);
                if (!$p) {
                    return response()->json(['success' => false, 'message' => 'Produk tidak ditemukan'], 404);
                }
                return response()->json(['success' => true, 'data' => $this->formatProduct($p)]);
            }
            $category = $request->query('category') ?: '';
            $q = \App\Models\Product::query();
            if ($category && $category !== 'all') {
                $q->where('category', $category)->where('is_active', 1);
            } else {
                $q->where('is_active', 1);
            }
            $products = $q->orderBy('sort_order', 'asc')->orderBy('id', 'asc')->get()->map(function($p) {
                return $this->formatProduct($p);
            });
            return response()->json(['success' => true, 'data' => $products]);
        }

        if ($request->isMethod('post')) {
            $this->requireAdmin($request);
            $errors = [];
            if (!$request->filled('name')) $errors[] = 'Nama produk wajib diisi.';
            if (!$request->filled('promo_price') && !$request->filled('price')) $errors[] = 'Harga produk wajib diisi.';
            if ($errors) {
                return response()->json(['success' => false, 'errors' => $errors], 422);
            }

            $new = \App\Models\Product::create([
                'name' => trim($request->input('name')),
                'description' => trim($request->input('description') ?? ''),
                'price' => trim($request->input('price') ?? ''),
                'promo_price' => trim($request->input('promo_price') ?: $request->input('price') ?: ''),
                'image' => trim($request->input('image') ?? 'assets/images/laptop.png'),
                'category' => trim($request->input('category') ?? 'ebook'),
                'shopee_url' => trim($request->input('shopee_url') ?? ''),
                'tokopedia_url' => trim($request->input('tokopedia_url') ?? ''),
                'va_details' => trim($request->input('va_details') ?? ''),
                'stock' => (int)($request->input('stock') ?? -1),
                'is_active' => $request->has('is_active') ? (int)$request->input('is_active') : 1,
                'sort_order' => (int)($request->input('sort_order') ?? 0),
            ]);

            return response()->json(['success' => true, 'message' => 'Produk berhasil ditambahkan.', 'data' => $this->formatProduct($new)], 201);
        }

        if ($request->isMethod('put')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada untuk update'], 400);
            }
            $p = \App\Models\Product::find($id);
            if (!$p) {
                return response()->json(['success' => false, 'message' => 'Produk tidak ditemukan'], 404);
            }

            $allowed = ['name','description','price','promo_price','image','category','shopee_url','tokopedia_url','va_details','stock','is_active','sort_order'];
            $data = [];
            foreach ($allowed as $f) {
                if ($request->has($f)) {
                    $val = $request->input($f);
                    $data[$f] = in_array($f, ['stock', 'is_active', 'sort_order']) ? (int)$val : trim($val ?? '');
                }
            }
            $p->update($data);
            return response()->json(['success' => true, 'message' => 'Produk berhasil diperbarui.', 'data' => $this->formatProduct($p)]);
        }

        if ($request->isMethod('delete')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            \App\Models\Product::where('id', $id)->delete();
            return response()->json(['success' => true, 'message' => 'Produk berhasil dihapus.']);
        }

        return response()->json(['success' => false, 'message' => 'Method tidak didukung'], 405);
    }

    // ── ORDERS ENDPOINT ───────────────────────────────────────────────────────

    public function orders(Request $request)
    {
        $action = $request->query('action') ?: $request->input('action');
        $id = $request->query('id') ?: $request->input('id');

        if ($request->isMethod('get')) {
            $this->requireAdmin($request);
            if ($action === 'summary') {
                $recent = \App\Models\Order::orderBy('created_at', 'desc')->limit(5)->get()->map(function($o) {
                    $o->items = json_decode($o->items_json, true) ?? [];
                    return $o;
                });
                $summary = [
                    'total'     => (int)\App\Models\Order::count(),
                    'pending'   => (int)\App\Models\Order::where('status', 'pending')->count(),
                    'confirmed' => (int)\App\Models\Order::where('status', 'confirmed')->count(),
                    'completed' => (int)\App\Models\Order::where('status', 'completed')->count(),
                    'cancelled' => (int)\App\Models\Order::where('status', 'cancelled')->count(),
                    'revenue'   => (int)\App\Models\Order::where('status', 'completed')->sum('total_price'),
                    'recent'    => $recent,
                ];
                return response()->json(['success' => true, 'data' => $summary]);
            }
            if ($id) {
                $o = \App\Models\Order::find($id);
                if (!$o) {
                    return response()->json(['success' => false, 'message' => 'Order tidak ditemukan'], 404);
                }
                $o->items = json_decode($o->items_json, true) ?? [];
                return response()->json(['success' => true, 'data' => $o]);
            }
            $status = $request->query('status') ?: '';
            $q = \App\Models\Order::query();
            if ($status) {
                $q->where('status', $status);
            }
            $orders = $q->orderBy('created_at', 'desc')->get()->map(function($o) {
                $o->items = json_decode($o->items_json, true) ?? [];
                return $o;
            });
            return response()->json(['success' => true, 'data' => $orders]);
        }

        if ($request->isMethod('post')) {
            $errors = [];
            if (!$request->filled('customer_name'))  $errors[] = 'Nama pelanggan wajib diisi.';
            if (!$request->filled('customer_phone')) $errors[] = 'Nomor WhatsApp pelanggan wajib diisi.';
            if (!$request->filled('items'))          $errors[] = 'Item pesanan wajib ada.';
            if ($errors) {
                return response()->json(['success' => false, 'errors' => $errors], 422);
            }

            $orderNumber = 'BLG-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -5));
            $items = $request->input('items');
            if (is_string($items)) {
                $items = json_decode($items, true) ?? [];
            }
            
            $total = 0;
            foreach ($items as $item) {
                $priceNum = (int)preg_replace('/[^0-9]/', '', $item['price'] ?? '0');
                $total += $priceNum * (int)($item['quantity'] ?? 1);
            }

            $new = \App\Models\Order::create([
                'order_number' => $orderNumber,
                'customer_name' => trim($request->input('customer_name')),
                'customer_phone' => trim($request->input('customer_phone')),
                'customer_email' => trim($request->input('customer_email') ?? ''),
                'items_json' => json_encode($items, JSON_UNESCAPED_UNICODE),
                'total_price' => $total,
                'payment_method' => trim($request->input('payment_method') ?? 'transfer'),
                'status' => 'pending',
                'notes' => trim($request->input('notes') ?? ''),
            ]);

            return response()->json(['success' => true, 'message' => 'Pesanan berhasil dibuat.', 'order_number' => $orderNumber, 'data' => $new], 201);
        }

        if ($request->isMethod('put')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            $o = \App\Models\Order::find($id);
            if (!$o) {
                return response()->json(['success' => false, 'message' => 'Order tidak ditemukan'], 404);
            }

            $allowed = ['status', 'notes', 'payment_method'];
            $data = [];
            foreach ($allowed as $f) {
                if ($request->has($f)) {
                    $data[$f] = trim($request->input($f));
                }
            }
            $o->update($data);
            return response()->json(['success' => true, 'message' => 'Status pesanan berhasil diperbarui.']);
        }

        if ($request->isMethod('delete')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            \App\Models\Order::where('id', $id)->delete();
            return response()->json(['success' => true, 'message' => 'Pesanan berhasil dihapus.']);
        }

        return response()->json(['success' => false, 'message' => 'Method tidak didukung'], 405);
    }

    // ── REGISTRATIONS ENDPOINT ────────────────────────────────────────────────

    public function registrations(Request $request)
    {
        $id = $request->query('id') ?: $request->input('id');

        if ($request->isMethod('get')) {
            $this->requireAdmin($request);
            if ($id) {
                $r = \App\Models\Registration::find($id);
                if (!$r) {
                    return response()->json(['success' => false, 'message' => 'Registrasi tidak ditemukan'], 404);
                }
                return response()->json(['success' => true, 'data' => $r]);
            }
            $regs = \App\Models\Registration::orderBy('created_at', 'desc')->get();
            return response()->json(['success' => true, 'data' => $regs]);
        }

        if ($request->isMethod('post')) {
            if (!$request->filled('name')) {
                return response()->json(['success' => false, 'message' => 'Nama wajib diisi.'], 422);
            }
            $new = \App\Models\Registration::create([
                'name' => trim($request->input('name')),
                'phone' => trim($request->input('phone') ?? ''),
                'email' => trim($request->input('email') ?? ''),
                'topic' => trim($request->input('topic') ?? ''),
                'referral' => trim($request->input('referral') ?? ''),
            ]);
            return response()->json(['success' => true, 'message' => 'Registrasi berhasil disimpan.', 'id' => $new->id], 201);
        }

        if ($request->isMethod('delete')) {
            $this->requireAdmin($request);
            if ($id) {
                \App\Models\Registration::where('id', $id)->delete();
                return response()->json(['success' => true, 'message' => 'Registrasi berhasil dihapus.']);
            }
            if ($request->query('all') === 'true') {
                \App\Models\Registration::truncate();
                return response()->json(['success' => true, 'message' => 'Semua registrasi berhasil dihapus.']);
            }
            return response()->json(['success' => false, 'message' => 'ID atau parameter all wajib ada'], 400);
        }

        return response()->json(['success' => false, 'message' => 'Method tidak didukung'], 405);
    }

    // ── SLIDES ENDPOINT ───────────────────────────────────────────────────────

    public function slides(Request $request)
    {
        $id = $request->query('id') ?: $request->input('id');

        if ($request->isMethod('get')) {
            $slides = \App\Models\Slide::orderBy('sort_order', 'asc')->orderBy('id', 'asc')->get()->map(function($s) {
                return $this->formatSlide($s);
            });
            return response()->json(['success' => true, 'data' => $slides]);
        }

        if ($request->isMethod('post')) {
            $this->requireAdmin($request);
            $outcomes = $request->input('outcomes') ?? '';
            if (is_array($outcomes)) {
                $outcomes = implode('|', $outcomes);
            }

            $new = \App\Models\Slide::create([
                'type' => $request->input('type') ?? 'original',
                'tech_text' => $request->input('tech_text') ?? '',
                'title' => $request->input('title') ?? '',
                'subtitle' => $request->input('subtitle') ?? '',
                'tagline' => $request->input('tagline') ?? '',
                'outcomes' => $outcomes,
                'event_date' => $request->input('event_date') ?? '',
                'old_price' => $request->input('old_price') ?? '',
                'new_price' => $request->input('new_price') ?? '',
                'bonus' => $request->input('bonus') ?? '',
                'btn_text' => $request->input('btn_text') ?? 'DAFTAR SEKARANG',
                'image' => $request->input('image') ?? '',
                'speaker_name' => $request->input('speaker_name') ?? '',
                'speaker_title1' => $request->input('speaker_title1') ?? '',
                'speaker_title2' => $request->input('speaker_title2') ?? '',
                'speaker_image' => $request->input('speaker_image') ?? '',
                'is_active' => $request->has('is_active') ? (int)$request->input('is_active') : 1,
                'sort_order' => (int)($request->input('sort_order') ?? 0),
            ]);

            return response()->json(['success' => true, 'data' => $this->formatSlide($new)], 201);
        }

        if ($request->isMethod('put')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            $s = \App\Models\Slide::find($id);
            if (!$s) {
                return response()->json(['success' => false, 'message' => 'Slide tidak ditemukan'], 404);
            }

            $allowed = ['type','tech_text','title','subtitle','tagline','outcomes','event_date','old_price','new_price','bonus','btn_text','image','speaker_name','speaker_title1','speaker_title2','speaker_image','is_active','sort_order'];
            $data = [];
            foreach ($allowed as $f) {
                if ($request->has($f)) {
                    $val = $request->input($f);
                    if ($f === 'outcomes' && is_array($val)) {
                        $val = implode('|', $val);
                    }
                    $data[$f] = in_array($f, ['is_active', 'sort_order']) ? (int)$val : $val;
                }
            }
            $s->update($data);
            return response()->json(['success' => true, 'data' => $this->formatSlide($s)]);
        }

        if ($request->isMethod('delete')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            \App\Models\Slide::where('id', $id)->delete();
            return response()->json(['success' => true, 'message' => 'Slide berhasil dihapus.']);
        }

        return response()->json(['success' => false, 'message' => 'Method tidak didukung'], 405);
    }

    // ── SESSIONS ENDPOINT ─────────────────────────────────────────────────────

    public function sessions(Request $request)
    {
        $id = $request->query('id') ?: $request->input('id');

        if ($request->isMethod('get')) {
            $sessions = \App\Models\Session::orderBy('sort_order', 'asc')->orderBy('id', 'asc')->get()->map(function($s) {
                return $this->formatSession($s);
            });
            return response()->json(['success' => true, 'data' => $sessions]);
        }

        if ($request->isMethod('post')) {
            $this->requireAdmin($request);
            if (!$request->filled('name')) {
                return response()->json(['success' => false, 'message' => 'Nama Sesi wajib diisi.'], 422);
            }
            $new = \App\Models\Session::create([
                'event_date' => $request->input('event_date') ?? '',
                'name' => trim($request->input('name')),
                'description' => trim($request->input('description') ?? ''),
                'bg_color' => $request->input('bg_color') ?? 'bg-yellow',
                'is_tall' => $request->has('is_tall') ? (int)$request->input('is_tall') : 0,
                'sort_order' => (int)($request->input('sort_order') ?? 0),
            ]);
            return response()->json(['success' => true, 'data' => $this->formatSession($new)], 201);
        }

        if ($request->isMethod('put')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            $s = \App\Models\Session::find($id);
            if (!$s) {
                return response()->json(['success' => false, 'message' => 'Sesi tidak ditemukan'], 404);
            }

            $allowed = ['event_date','name','description','bg_color','is_tall','sort_order'];
            $data = [];
            foreach ($allowed as $f) {
                if ($request->has($f)) {
                    $val = $request->input($f);
                    $data[$f] = in_array($f, ['is_tall', 'sort_order']) ? (int)$val : trim($val ?? '');
                }
            }
            $s->update($data);
            return response()->json(['success' => true, 'data' => $this->formatSession($s)]);
        }

        if ($request->isMethod('delete')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            \App\Models\Session::where('id', $id)->delete();
            return response()->json(['success' => true, 'message' => 'Sesi berhasil dihapus.']);
        }

        return response()->json(['success' => false, 'message' => 'Method tidak didukung'], 405);
    }

    // ── TOPICS ENDPOINT ───────────────────────────────────────────────────────

    public function topics(Request $request)
    {
        $id = $request->query('id') ?: $request->input('id');

        if ($request->isMethod('get')) {
            $topics = \App\Models\Topic::orderBy('sort_order', 'asc')->orderBy('id', 'asc')->get();
            return response()->json(['success' => true, 'data' => $topics]);
        }

        if ($request->isMethod('post')) {
            $this->requireAdmin($request);
            if (!$request->filled('value') || !$request->filled('label')) {
                return response()->json(['success' => false, 'message' => 'Value dan label wajib diisi.'], 422);
            }
            try {
                \App\Models\Topic::create([
                    'value' => trim($request->input('value')),
                    'label' => trim($request->input('label')),
                    'sort_order' => (int)($request->input('sort_order') ?? 0),
                ]);
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Value sudah ada.'], 409);
            }
            return response()->json(['success' => true, 'message' => 'Topik berhasil ditambahkan.'], 201);
        }

        if ($request->isMethod('put')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            $t = \App\Models\Topic::find($id);
            if (!$t) {
                return response()->json(['success' => false, 'message' => 'Topik tidak ditemukan'], 404);
            }
            $t->update([
                'value' => trim($request->input('value')),
                'label' => trim($request->input('label')),
                'sort_order' => (int)($request->input('sort_order') ?? 0),
            ]);
            return response()->json(['success' => true, 'message' => 'Topik berhasil diperbarui.']);
        }

        if ($request->isMethod('delete')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            \App\Models\Topic::where('id', $id)->delete();
            return response()->json(['success' => true, 'message' => 'Topik berhasil dihapus.']);
        }

        return response()->json(['success' => false, 'message' => 'Method tidak didukung'], 405);
    }

    // ── NEWS ENDPOINT ─────────────────────────────────────────────────────────

    public function news(Request $request)
    {
        $id = $request->query('id') ?: $request->input('id');

        if ($request->isMethod('get')) {
            $news = \App\Models\News::orderBy('created_at', 'desc')->orderBy('id', 'desc')->get();
            return response()->json(['success' => true, 'data' => $news]);
        }

        if ($request->isMethod('post')) {
            $this->requireAdmin($request);
            if (!$request->filled('title')) {
                return response()->json(['success' => false, 'message' => 'Judul wajib diisi.'], 422);
            }
            $new = \App\Models\News::create([
                'title' => trim($request->input('title')),
                'description' => trim($request->input('description') ?? ''),
                'news_date' => trim($request->input('news_date') ?: date('d M Y')),
                'image' => trim($request->input('image') ?? ''),
            ]);
            return response()->json(['success' => true, 'message' => 'Berita berhasil ditambahkan.', 'id' => $new->id], 201);
        }

        if ($request->isMethod('put')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            $n = \App\Models\News::find($id);
            if (!$n) {
                return response()->json(['success' => false, 'message' => 'Berita tidak ditemukan'], 404);
            }
            $n->update([
                'title' => trim($request->input('title')),
                'description' => trim($request->input('description') ?? ''),
                'news_date' => trim($request->input('news_date') ?? ''),
                'image' => trim($request->input('image') ?? ''),
            ]);
            return response()->json(['success' => true, 'message' => 'Berita berhasil diperbarui.']);
        }

        if ($request->isMethod('delete')) {
            $this->requireAdmin($request);
            if (!$id) {
                return response()->json(['success' => false, 'message' => 'ID wajib ada'], 400);
            }
            \App\Models\News::where('id', $id)->delete();
            return response()->json(['success' => true, 'message' => 'Berita berhasil dihapus.']);
        }

        return response()->json(['success' => false, 'message' => 'Method tidak didukung'], 405);
    }

    // ── SETTINGS ENDPOINT ─────────────────────────────────────────────────────

    public function settings(Request $request)
    {
        $key = $request->query('key');

        if ($request->isMethod('get')) {
            if ($key) {
                $value = \App\Models\Setting::where('key_name', $key)->value('value');
                return response()->json(['success' => true, 'value' => $value]);
            }
            $settings = \App\Models\Setting::pluck('value', 'key_name')->toArray();
            return response()->json(['success' => true, 'data' => $settings]);
        }

        if ($request->isMethod('post') || $request->isMethod('put')) {
            $this->requireAdmin($request);
            if ($request->has('data') && is_array($request->input('data'))) {
                // Bulk update
                foreach ($request->input('data') as $k => $v) {
                    \App\Models\Setting::updateOrCreate(
                        ['key_name' => $k],
                        ['value' => $v]
                    );
                }
                return response()->json(['success' => true, 'message' => 'Pengaturan berhasil disimpan.']);
            }
            if ($request->filled('key') && $request->has('value')) {
                \App\Models\Setting::updateOrCreate(
                    ['key_name' => $request->input('key')],
                    ['value' => $request->input('value')]
                );
                return response()->json(['success' => true, 'message' => 'Pengaturan berhasil disimpan.']);
            }
            return response()->json(['success' => false, 'message' => 'Data tidak valid'], 400);
        }

        return response()->json(['success' => false, 'message' => 'Method tidak didukung'], 405);
    }
}
