<?php

namespace App\Http\Controllers;
use App\Services\PredictionService;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PredictionController extends Controller
{
    public function index()
    {
        $service = new PredictionService();
        $data = $service->getMonthlyUsage();
        return view('prediksi-barang', compact('data'));
    }

    public function runPrediction(Request $request)
    {
        $kodeBarangArray = $request->kode_barang;
        foreach ($kodeBarangArray as $kode) {
            $historyCount = DB::table('item_usage_monthly')
                ->where('kode', $kode)
                ->count();
            if ($historyCount < 6) {
                $barang = DB::table('items')
                    ->where('kode', $kode)
                    ->first();
                return response()->json([
                    'error' =>
                        'Barang "' . $barang->nama_barang .
                        '" tidak dapat diprediksi karena data riwayat pemakaian tidak lengkap.'
                ]);
            }
        }
        $kode_barang = implode(',', $kodeBarangArray);
        $bulan = $request->bulan;
        $tahun = $request->tahun;
        $pythonFile = base_path('machine_learning/predict.py');
        // $command = "python \"$pythonFile\" \"$kode_barang\" $bulan $tahun 2>&1";
        $command = "python3 \"$pythonFile\" \"$kode_barang\" $bulan $tahun 2>&1";
        $output = shell_exec($command);
        if (!$output) {
            return response()->json([
                "error" => "Python tidak mengembalikan output"
            ]);
        }
        $json = json_decode($output, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return response()->json([
                "error" => $output
            ]);
        }
        \Log::info(
            "DEBUG PYTHON",
            [
                "load_model" => $json['debug']['load_model'],
                "meta_query" => $json['debug']['meta_query'],
                "history_query" => $json['debug']['history_query'],
                "total" => $json['debug']['total']
            ]
        );
        foreach ($json['data'] as &$item) {
            $item['prediction'] = (int) round($item['prediction'] * 2.5);
        }
        return response()->json($json['data']);
    }

    public function save(Request $request)
    {
        foreach ($request->results as $item) {
            DB::table('prediction_results')->updateOrInsert(
                [
                    'kode' => $item['kode'],
                    'bulan_prediksi' => $item['bulan'],
                    'tahun_prediksi' => $item['tahun'],
                ],
                [
                    'jumlah_prediksi' => round($item['prediction']),
                    'tanggal_prediksi' => now()
                ]
            );
        }
        return response()->json([
            'success' => true
        ]);
    }

    public function destroy($id)
    {
        DB::table('prediction_results')->where('id', $id)->delete();
        return redirect()->back()->with('success', 'Data riwayat prediksi berhasil dihapus');
    }
}

