<?php

namespace App\Http\Controllers;

use App\Models\EventBlock;
use App\Models\Event;
use App\Models\StadiumBlock;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class EventBlockController extends Controller
{
    public function index()
    {
        return view('admin.event_blocks');
    }

    public function getBlocks(Request $request)
    {
        if ($request->ajax()) {
            $data = EventBlock::with(['event', 'stadiumBlock'])->latest()->get();

            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('event_name', fn($row) => $row->event->name ?? '-')
                ->addColumn('block_name', fn($row) => $row->stadiumBlock->name ?? '-')
                ->addColumn('action', function ($row) {
                    return '
                        <button class="btn btn-sm btn-primary editBlock" data-id="' . $row->id . '">Edit</button>
                        <button class="btn btn-sm btn-danger deleteBlock" data-id="' . $row->id . '">Delete</button>
                    ';
                })
                ->rawColumns(['action'])
                ->make(true);
        }
    }

    public function store(Request $request)
    {
        $request->validate([
            'event_id' => 'required|exists:events,id',
            'stadium_block_id' => 'required|exists:stadium_blocks,id',
            'total_tickets' => 'required|integer|min:1',
            'price' => 'required|numeric|min:0',
        ]);

        EventBlock::create($request->all());
        return response()->json(['success' => 'Block added successfully!']);
    }

    public function edit($id)
    {
        $block = EventBlock::findOrFail($id);
        return response()->json(['block' => $block]);
    }

    public function update(Request $request, $id)
    {
        $block = EventBlock::findOrFail($id);
        $request->validate([
            'event_id' => 'required|exists:events,id',
            'stadium_block_id' => 'required|exists:stadium_blocks,id',
            'total_tickets' => 'required|integer|min:1',
            'price' => 'required|numeric|min:0',
        ]);
        $block->update($request->all());
        return response()->json(['success' => 'Block updated successfully!']);
    }

    public function destroy($id)
    {
        EventBlock::findOrFail($id)->delete();
        return response()->json(['success' => 'Block deleted successfully!']);
    }
}
