<?php

namespace App\Http\Controllers;

use App\Models\Period;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class PeriodsController extends Controller
{
    
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $periods = Period::active()->orderBy('code')->get();
            
            $result = [];
            $no = 1;
            foreach ($periods as $row) {
                $result[] = [
                    $no++,
                    '<a href="' . route('periods.show', $row->id) . '">' . $row->code . '</a>',
                    $row->name,
                    $row->description ?? '-',
                    '<span class="badge ' . $row->status_badge . '">' . $row->status . '</span>',
                    $row->created_at->format('M jS Y, H:i'),
                ];
            }

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

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

    public function create()
    {
        return view('m-periods.form', [
            'data' => json_decode(json_encode([
                'id' => 0,
                'code' => '',
                'name' => '',
                'description' => '',
                'is_active' => true
            ])),
            'variables' => $this->variables([
                'judul' => 'Add Period'
            ])
        ]);
    }

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

        $rules = [
            'code' => $period ? 
                'required|string|max:20|unique:m_periods,code,' . $period->id . ',id,delete_flag,false' :
                'required|string|max:20|unique:m_periods,code,NULL,id,delete_flag,false',
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:255',
            'is_active' => 'boolean'
        ];

        $messages = [];
        $saveData = $request->validate($rules, $messages);

        // Set default values
        $saveData['is_active'] = $request->has('is_active');

        try {
            if ($period) {
                $period->update(array_merge($saveData, [
                    'updated_by' => $this->logged_user_id,
                ]));
            } else {
                Period::create(array_merge($saveData, [
                    'delete_flag' => false,
                    'created_by' => $this->logged_user_id,
                    'updated_by' => $this->logged_user_id,
                ]));
            }

            $notif = $period ? '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(Period $period)
    {
        if ($period->delete_flag) {
            return redirect()->route('periods.index')
                ->with('error', 'Period not found.');
        }

        return view('m-periods.show', [
            'data' => $period,
            'variables' => $this->variables([
                'judul' => 'View Period'
            ])
        ]);
    }

    public function edit(Period $period)
    {
        if ($period->delete_flag) {
            return redirect()->route('periods.index')
                ->with('error', 'Period not found.');
        }

        return view('m-periods.form', [
            'data' => $period,
            'variables' => $this->variables([
                'judul' => 'Edit Period'
            ])
        ]);
    }

    public function destroy(Period $period)
    {
        // Check if period is being used by raw materials
        $usageCount = $period->rawMaterials()->where('delete_flag', false)->count();
        if ($usageCount > 0) {
            return response()->json([
                'warning', 
                "Cannot delete period. It is being used by {$usageCount} raw material(s)."
            ]);
        }

        $period->update([
            'delete_flag' => true,
            'updated_by' => $this->logged_user_id
        ]);

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

    private function variables($variables = [])
    {
        $defaultVariables = [
            'header_routes' => '
                <li class="breadcrumb-item">Master Data</li>
                <li class="breadcrumb-item active">Periods</li>
            ',
            'judul' => 'Periods'
        ];

        return array_merge($defaultVariables, $variables);
    }

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

        return $e;
    }
}