<?php

namespace App\Http\Controllers;

use App\Models\Fstr;
use App\Models\FstrDetail;
use App\Models\RawMaterial;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

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

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

            $total = $query->count();

            // Sorting
            $columns = ['id', 'code', 'name', 'total_cost', 'is_active'];
            $orderColumn = $columns[$request->order[0]['column']] ?? 'code';
            $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('fstrs.show', $row->id) . '">' . $row->code . '</a>',
                    $row->name,
                    $row->description ?? '-',
                    $row->formatted_total_cost,
                    $activeBadge,
                ];
            }

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

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

    public function create()
    {
        $variables['judul'] = 'Add FSTR (Item Olahan)';
        $variables['rawMaterials'] = RawMaterial::where('delete_flag', 0)->orderBy('code')->get();
        
        return view('m-fstrs.form', [
            'data' => json_decode(json_encode(array('id' => 0))),
            'variables' => $this->variables($variables)
        ]);
    }

    public function edit(Fstr $fstr)
    {
        $fstr->load('fstrDetails.rawMaterial');
        $variables['judul'] = 'Edit FSTR (Item Olahan)';
        $variables['rawMaterials'] = RawMaterial::where('delete_flag', 0)->orderBy('code')->get();
        
        return view('m-fstrs.form', [
            'data' => $fstr,
            'variables' => $this->variables($variables)
        ]);
    }

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

        $rules = [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
            'details' => 'required|array|min:1',
            'details.*.raw_material_id' => 'required|exists:m_raw_materials,id',
            'details.*.quantity' => 'required|numeric|min:0.0001',
            'details.*.uom' => 'required|string|max:10',
            'details.*.unit_cost' => 'required|numeric|min:0',
            'details.*.notes' => 'nullable|string|max:255',
        ];

        $messages = [
            'details.required' => 'At least one raw material detail is required.',
            'details.min' => 'At least one raw material detail is required.',
        ];
        
        $saveData = $request->validate($rules, $messages);

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

        try {
            DB::beginTransaction();

            if ($fstr) {
                $fstr->update(array_merge($saveData, [
                    'updated_by' => $this->logged_user_id,
                ]));
                
                // Delete existing details
                FstrDetail::where('fstr_id', $fstr->id)->update(['delete_flag' => 1]);
            } else {
                $fstr = Fstr::create(array_merge($saveData, [
                    'created_by' => $this->logged_user_id,
                ]));
            }

            // Create new details
            $totalCost = 0;
            foreach ($saveData['details'] as $detail) {
                $detailCost = $detail['quantity'] * $detail['unit_cost'];
                $totalCost += $detailCost;

                FstrDetail::create([
                    'fstr_id' => $fstr->id,
                    'raw_material_id' => $detail['raw_material_id'],
                    'quantity' => $detail['quantity'],
                    'uom' => $detail['uom'],
                    'unit_cost' => $detail['unit_cost'],
                    'total_cost' => $detailCost,
                    'notes' => $detail['notes'] ?? null,
                    'created_by' => $this->logged_user_id,
                ]);
            }

            // Update total cost
            $fstr->update(['total_cost' => $totalCost]);

            DB::commit();
            
            $notif = $prm_id ? 'Updated successfully.' : 'Successfully created.';
            return response()->json(['success', $notif]);
            
        } catch (\Exception $e) {
            DB::rollBack();
            $notif = $this->getErrorCatch($e->getMessage());
            return response()->json(['warning', $notif]);
        }
    }

    public function show(Fstr $fstr)
    {
        $fstr->load(['fstrDetails.rawMaterial', 'creator', 'modificator']);
        $variables['judul'] = 'View FSTR: ' . $fstr->code;
        return view('m-fstrs.show', [
            'data' => $fstr,
            'variables' => $this->variables($variables)
        ]);
    }

    public function destroy(Fstr $fstr)
    {
        DB::beginTransaction();
        try {
            // Soft delete FSTR and its details
            $fstr->update([
                'delete_flag' => 1,
                'updated_by' => $this->logged_user_id
            ]);

            FstrDetail::where('fstr_id', $fstr->id)->update([
                'delete_flag' => 1,
                'updated_by' => $this->logged_user_id
            ]);

            DB::commit();

            return redirect()->route('fstrs.index')
                ->with('success', 'Successfully deleted');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->route('fstrs.index')
                ->with('error', 'Failed to delete: ' . $e->getMessage());
        }
    }

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

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

        return $e;
    }
}