<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

class PredictionService
{
    public function getMonthlyUsage()
    {
        return DB::table('item_usage_monthly')
            ->select(
                'kode',
                'tahun',
                'bulan',
                'total_pemakaian as total_pakai'
            )
            ->orderBy('kode')
            ->orderBy('tahun')
            ->orderBy('bulan')
            ->get();
    }

    public function createLagDataset($kodeBarang)
    {
        $data = DB::table('item_usage_monthly')
            ->select(
                'tahun',
                'bulan',
                'total_pemakaian as total'
            )
            ->where('kode', $kodeBarang)
            ->orderBy('tahun')
            ->orderBy('bulan')
            ->get();
        $dataset = [];
        for ($i = 6; $i < count($data); $i++) {
            $dataset[] = [
                'lag1' => $data[$i - 1]->total,
                'lag2' => $data[$i - 2]->total,
                'lag3' => $data[$i - 3]->total,
                'lag4' => $data[$i - 4]->total,
                'lag5' => $data[$i - 5]->total,
                'lag6' => $data[$i - 6]->total,
                'target' => $data[$i]->total
            ];
        }
        return $dataset;
    }

    public function predictWithPython($dataset)
    {
        $jsonData = json_encode($dataset);
        $pythonScript = base_path('machine_learning/predict.py');
        $process = proc_open(
            "python \"$pythonScript\"",
            [
                0 => ["pipe", "r"],
                1 => ["pipe", "w"],
                2 => ["pipe", "w"]
            ],
            $pipes
        );
        fwrite($pipes[0], $jsonData);
        fclose($pipes[0]);
        $output = stream_get_contents($pipes[1]);
        fclose($pipes[1]);
        $error = stream_get_contents($pipes[2]);
        fclose($pipes[2]);
        proc_close($process);
        if ($error) {
            return ["error" => $error];
        }
        $decoded = json_decode($output, true);
        return $decoded['prediction'] ?? null;
    }

    public function evaluateModels($dataset)
    {
        $jsonData = json_encode($dataset);
        $script = base_path('machine_learning/predict.py');
        $command = "python \"$script\" '" . addslashes($jsonData) . "'";
        $output = shell_exec($command);
        return json_decode($output, true);
    }
}