<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\StadiumBlock;
use App\Models\Stadium;
use Illuminate\Support\Facades\File;
use Yajra\DataTables\Facades\DataTables;

class StadiumBlockController extends Controller
{
    // List (DataTable)
    public function getBlocks(Request $request)
    {
        if ($request->ajax()) {
            $data = StadiumBlock::with('stadium')->select('stadium_blocks.*');
            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('stadium_name', fn($row) => $row->stadium->name ?? '-')
                ->addColumn('image', function ($row) {
                    return $row->image ? '<img src="' . asset($row->image) . '" width="60">' : '';
                })
                ->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(['image', 'action'])
                ->make(true);
        }
    }

    // Store
    public function store(Request $request)
    {
        $request->validate([
            'stadium_id' => 'required|exists:stadiums,id',
            'name'       => 'required|string|max:255',
            'position'   => 'nullable|string|max:255',
            'capacity'   => 'required|integer|min:0',
            'base_price' => 'required|numeric|min:0',
            'photo'      => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $imagePath = null;
        if ($request->hasFile('photo')) {
            $image = $request->photo;
            $imageName = time() . '-' . rand(100, 999) . '.' . $image->extension();
            $uploadPath = public_path('assets/upload/blocks/');
            if (!File::exists($uploadPath)) File::makeDirectory($uploadPath, 0755, true);
            $image->move($uploadPath, $imageName);
            $imagePath = 'assets/upload/blocks/' . $imageName;
        }

        StadiumBlock::create([
            'stadium_id' => $request->stadium_id,
            'name'       => $request->name,
            'position'   => $request->position,
            'capacity'   => $request->capacity,
            'base_price' => $request->base_price,
            'image'      => $imagePath,
        ]);

        return response()->json(['success' => 'Block added successfully!']);
    }

    // Update
    public function update(Request $request, $id)
    {
        $block = StadiumBlock::findOrFail($id);

        $request->validate([
            'stadium_id' => 'required|exists:stadiums,id',
            'name'       => 'required|string|max:255',
            'position'   => 'nullable|string|max:255',
            'capacity'   => 'required|integer|min:0',
            'base_price' => 'required|numeric|min:0',
            'photo'      => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $imagePath = $block->image;
        if ($request->hasFile('photo')) {
            $image = $request->photo;
            $imageName = time() . '-' . rand(100, 999) . '.' . $image->extension();
            $uploadPath = public_path('assets/upload/blocks/');
            if (!File::exists($uploadPath)) File::makeDirectory($uploadPath, 0755, true);

            if ($block->image && File::exists(public_path($block->image))) {
                File::delete(public_path($block->image));
            }

            $image->move($uploadPath, $imageName);
            $imagePath = 'assets/upload/blocks/' . $imageName;
        }

        $block->update([
            'stadium_id' => $request->stadium_id,
            'name'       => $request->name,
            'position'   => $request->position,
            'capacity'   => $request->capacity,
            'base_price' => $request->base_price,
            'image'      => $imagePath,
        ]);

        return response()->json(['success' => 'Block updated successfully!']);
    }

    // Delete
    public function destroy($id)
    {
        $block = StadiumBlock::findOrFail($id);
        if ($block->image && File::exists(public_path($block->image))) {
            File::delete(public_path($block->image));
        }
        $block->delete();
        return response()->json(['success' => 'Block deleted successfully!']);
    }
}
