<?php

namespace App\Http\Controllers;

use App\Models\RangeDoi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RangeDoisController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = RangeDoi::select('m_range_dois.*')
                ->where('delete_flag', 0);

            // Searching
            if ($request->has('search') && $request->search['value'] != '') {
                $search = $request->search['value'];
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'ilike', "%{$search}%")
                        ->orWhere('description', 'ilike', "%{$search}%");
                });
            }

            $total = $query->count();

            // Sorting
            $columns = ['id', 'name', 'min_days', 'max_days', 'color_code', 'is_active'];
            $orderColumn = $columns[$request->order[0]['column']] ?? 'min_days';
            $orderDir = $request->order[0]['dir'] ?? 'asc';

            $query->orderBy($orderColumn, $orderDir);

            // Pagination
            $start = $request->start;
            $length = $request->length;
            $data = $query->skip($start)->take($length)->get();

            // Format data
            $result = [];
            $no = $start + 1;
            foreach ($data as $row) {
                $activeBadge = $row->is_active ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-secondary">Inactive</span>';
                
                $result[] = [
                    $no++,
                    '<a href="' . route('range_dois.show', $row->id) . '">' . $row->name . '</a>',
                    number_format($row->min_days, 2),
                    $row->max_days == 999999 ? '∞' : number_format($row->max_days, 2),
                    $row->range_display,
                    $row->color_badge,
                    $activeBadge,
                ];
            }

            return response()->json([
                "draw" => intval($request->draw),
                "recordsTotal" => $total,
                "recordsFiltered" => $total,
                "data" => $result,
            ]);
        }

        return view('m-range-dois.index', [
            'variables' => $this->variables()
        ]);
    }

    public function create()
    {
        $variables['judul'] = 'Add Range DOI';
        
        return view('m-range-dois.form', [
            'data' => json_decode(json_encode(array('id' => 0))),
            'variables' => $this->variables($variables)
        ]);
    }

    public function edit(RangeDoi $rangeDoi)
    {
        $variables['judul'] = 'Edit Range DOI';
        
        return view('m-range-dois.form', [
            'data' => $rangeDoi,
            'variables' => $this->variables($variables)
        ]);
    }

    public function store(Request $request, $prm_id)
    {
        $rangeDoi = null;
        if ($prm_id)
            $rangeDoi = RangeDoi::findOrFail($prm_id);

        $rules = [
            'name' => 'required|string|max:100',
            'min_days' => 'required|numeric|min:0',
            'max_days' => 'required|numeric|min:0|gte:min_days',
            'color_code' => 'nullable|string|max:7|regex:/^#[0-9A-Fa-f]{6}$/',
            'description' => 'nullable|string|max:500',
            'is_active' => 'boolean',
        ];

        $messages = [
            'max_days.gte' => 'Max days must be greater than or equal to min days.',
            'color_code.regex' => 'Color code must be a valid hex color (e.g., #FF0000).',
        ];
        
        $saveData = $request->validate($rules, $messages);

        // Set default values
        $saveData['is_active'] = $request->has('is_active');
        $saveData['color_code'] = $saveData['color_code'] ?? '#6c757d';

        try {
            if ($rangeDoi) {
                $rangeDoi->update(array_merge($saveData, [
                    'updated_by' => $this->logged_user_id,
                ]));
            } else {
                RangeDoi::create(array_merge($saveData, [
                    'created_by' => $this->logged_user_id,
                ]));
            }
            
            $notif = $rangeDoi ? 'Updated successfully.' : 'Successfully created.';
            return response()->json(['success', $notif]);
            
        } catch (\Exception $e) {
            $notif = $this->getErrorCatch($e->getMessage());
            return response()->json(['warning', $notif]);
        }
    }

    public function show(RangeDoi $rangeDoi)
    {
        $rangeDoi->load(['creator', 'modificator']);
        $variables['judul'] = 'View Range DOI: ' . $rangeDoi->name;
        return view('m-range-dois.show', [
            'data' => $rangeDoi,
            'variables' => $this->variables($variables)
        ]);
    }

    public function destroy(RangeDoi $rangeDoi)
    {
        $rangeDoi->update([
            'delete_flag' => 1,
            'updated_by' => $this->logged_user_id
        ]);

        return redirect()->route('range_dois.index')
            ->with('success', 'Successfully deleted');
    }

    private function variables($variables = null)
    {
        $variables['header_routes'] = ' 
								<li class="breadcrumb-item">Master Data</li>  
								<li class="breadcrumb-item active">Range DOI</li>
							 ';
        return $variables;
    }

    private function getErrorCatch($e)
    {
        if (strpos($e, '#error#') !== false) {
            $e = explode('#error#', $e);
            $e = $e[1];
        }

        return $e;
    }
}