<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MasterController extends Controller
{
    protected $masters = [
        'booking-categories' => ['model' => 'BookingCategory', 'title' => 'Category Master', 'has_price' => true],
        'paper-sizes' => ['model' => 'PaperSize', 'title' => 'Paper Size Master', 'has_price' => true],
        'paper-types' => ['model' => 'PaperType', 'title' => 'Paper Type Master', 'has_price' => true],
        'paper-brands' => ['model' => 'PaperBrand', 'title' => 'Paper Brand Master', 'has_price' => true],
        'paper-gsms' => ['model' => 'PaperGsm', 'title' => 'GSM Master', 'has_price' => true],
        'print-types' => ['model' => 'PrintType', 'title' => 'Print Type Master', 'has_price' => true],
        'color-types' => ['model' => 'ColorType', 'title' => 'Color Type Master', 'has_price' => true],
        'print-methods' => ['model' => 'PrintMethod', 'title' => 'Printing Machine Master', 'has_price' => true],
        'laminations' => ['model' => 'Lamination', 'title' => 'Lamination Master', 'has_price' => true],
        'lamination-sides' => ['model' => 'LaminationSide', 'title' => 'Lamination Side Master', 'has_price' => true],
        'bindings' => ['model' => 'Binding', 'title' => 'Binding Master', 'has_price' => true],
        'carbon-copies' => ['model' => 'CarbonCopy', 'title' => 'Carbon Copy Master', 'has_price' => true],
        'foldings' => ['model' => 'Folding', 'title' => 'Folding Master', 'has_price' => true],
        'corner-types' => ['model' => 'CornerType', 'title' => 'Corner Type Master', 'has_price' => true],
        'payment-terms' => ['model' => 'PaymentTerm', 'title' => 'Payment Terms Master', 'has_price' => false],
        'delivery-types' => ['model' => 'DeliveryType', 'title' => 'Delivery Type Master', 'has_price' => false],
        'job-priorities' => ['model' => 'JobPriority', 'title' => 'Job Priority Master', 'has_price' => false],
        'other-cost-masters' => ['model' => 'OtherCostMaster', 'title' => 'Other Cost Master', 'has_price' => true],
        'job-status-masters' => ['model' => 'JobStatusMaster', 'title' => 'Job Status Master', 'has_price' => false],
    ];

    protected function getModelClass($slug)
    {
        if (!isset($this->masters[$slug])) abort(404);
        return '\\App\\Models\\' . $this->masters[$slug]['model'];
    }

    protected function hasPrice($slug): bool
    {
        return !empty($this->masters[$slug]['has_price']);
    }

    public function index(Request $request, $slug)
    {
        if (!isset($this->masters[$slug])) abort(404);
        $title = $this->masters[$slug]['title'];
        $hasPrice = $this->hasPrice($slug);

        if ($request->ajax()) {
            $modelClass = $this->getModelClass($slug);
            $data = $modelClass::orderBy('sort_order', 'asc')->orderBy('name', 'asc')->get();

            return datatables()->of($data)
                ->addIndexColumn()
                ->editColumn('created_at', function ($row) {
                    return $row->created_at ? $row->created_at->format('d-M-Y H:i') : '-';
                })
                ->addColumn('action', function ($row) {
                    return '';
                })
                ->rawColumns(['action'])
                ->make(true);
        }

        return view('master.index', compact('slug', 'title', 'hasPrice'));
    }

    public function store(Request $request, $slug)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'sort_order' => 'nullable|integer',
        ];
        if ($this->hasPrice($slug)) {
            $rules['price'] = 'nullable|numeric|min:0';
        }
        $request->validate($rules);

        $modelClass = $this->getModelClass($slug);

        $fields = ['name', 'description', 'sort_order', 'status'];
        if ($this->hasPrice($slug)) {
            $fields[] = 'price';
        }
        $data = $request->only($fields);
        $data['status'] = $request->has('status') ? 1 : 0;
        if (!$data['sort_order']) {
            $data['sort_order'] = 0;
        }
        if ($this->hasPrice($slug)) {
            $data['price'] = $request->input('price', 0) ?: 0;
        }

        $modelClass::create($data);

        return response()->json(['success' => true, 'message' => 'Record added successfully']);
    }

    public function update(Request $request, $slug, $id)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'sort_order' => 'nullable|integer',
        ];
        if ($this->hasPrice($slug)) {
            $rules['price'] = 'nullable|numeric|min:0';
        }
        $request->validate($rules);

        $modelClass = $this->getModelClass($slug);
        $record = $modelClass::findOrFail($id);

        $fields = ['name', 'description', 'sort_order', 'status'];
        if ($this->hasPrice($slug)) {
            $fields[] = 'price';
        }
        $data = $request->only($fields);
        $data['status'] = $request->has('status') ? 1 : 0;
        if (!$data['sort_order']) {
            $data['sort_order'] = 0;
        }
        if ($this->hasPrice($slug)) {
            $data['price'] = $request->input('price', 0) ?: 0;
        }

        $record->update($data);

        return response()->json(['success' => true, 'message' => 'Record updated successfully']);
    }

    public function destroy($slug, $id)
    {
        $modelClass = $this->getModelClass($slug);
        $record = $modelClass::findOrFail($id);
        $record->delete();

        return response()->json(['success' => true, 'message' => 'Record deleted successfully']);
    }

    public function toggleStatus(Request $request, $slug, $id)
    {
        $modelClass = $this->getModelClass($slug);
        $record = $modelClass::findOrFail($id);
        $record->update(['status' => $request->status]);

        return response()->json(['success' => true, 'message' => 'Status updated successfully']);
    }
}
