<?php

namespace App\Http\Controllers;

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

class ResellerController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $resellers = Reseller::all();

        $headers = ['Nama Reseller', 'Nomor Telepon', 'Alamat', 'Aksi'];

        $rows = $resellers->map(function ($reseller) {
            return [
                'cols' => [
                    $reseller->name,
                    $reseller->phone ?? '-',
                    substr($reseller->address ?? '-', 0, 50),
                ],
                'actions' => view('components.action-button', [
                    'id' => $reseller->id,
                    'resource' => 'resellers'
                ])->render(),
            ];
        });

        return view('resellers.index', compact('headers', 'rows'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('resellers.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'address' => 'nullable|string',
            'phone' => 'nullable|string|max:30',
            'maps' => 'nullable|string',
        ]);

        Reseller::create($validated);

        return redirect()->route('resellers.index')->with('success', 'Reseller created successfully');
    }

    /**
     * Display the specified resource.
     */
    public function show(Reseller $reseller)
    {
        return view('resellers.show', compact('reseller'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Reseller $reseller)
    {
        return view('resellers.edit', compact('reseller'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Reseller $reseller)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'address' => 'nullable|string',
            'phone' => 'nullable|string|max:30',
            'maps' => 'nullable|string',
        ]);

        $reseller->update($validated);

        return redirect()->route('resellers.index')->with('success', 'Reseller updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Reseller $reseller)
    {
        $reseller->delete();
        return redirect()->route('resellers.index')->with('success', 'Reseller deleted successfully');
    }
}
