<?php

// namespace App\Http\Controllers\User;

// use App\Http\Controllers\Controller;
// use Illuminate\Support\Facades\Http;
// use Illuminate\Support\Facades\Auth;
// use Illuminate\Support\Facades\Session;
// use App\Models\DataPenjualan;
// use App\Models\HasilPrediksi;
// use Carbon\Carbon;

// class PrediksiControllers extends Controller
// {
//     public function index()
//     {
//         $count = DataPenjualan::where('user_id', Auth::id())->count();

//         $is_verified = $count >= 365;

//         $prediction_ready = $this->checkPredictionStatus();

//         $hasilPrediksi = HasilPrediksi::where('user_id', Auth::id())
//             ->orderBy('tanggal', 'asc')
//             ->get();

//         return view('user.prediksi.index', compact(
//             'is_verified',
//             'count',
//             'hasilPrediksi',
//             'prediction_ready'
//         ));
//     }

//     private function checkPredictionStatus()
//     {
//         return Session::get('prediction_ready', false);
//     }

//     public function getForecast()
//     {
//         try {

//             $count = DataPenjualan::where('user_id', Auth::id())->count();

//             if ($count < 365) {

//                 return response()->json([
//                     'error' => 'Minimal data penjualan harus 365 hari.'
//                 ], 400);
//             }

//             if (!$this->checkPredictionStatus()) {

//                 return response()->json([
//                     'error' => 'Ada data baru. Silakan klik tombol "Siapkan Prediksi" terlebih dahulu pada menu Master Data.'
//                 ], 400);
//             }

//             $userData = DataPenjualan::where('user_id', Auth::id())
//                 ->orderBy('tanggal', 'asc')
//                 ->get(['tanggal', 'jumlah'])
//                 ->map(fn($item) => [
//                     'tanggal' => Carbon::parse($item->tanggal)->format('Y-m-d'),
//                     'jumlah' => $item->jumlah
//                 ]);

//             $response = Http::timeout(200)->post(
//                 "http://127.0.0.1:5000/predict",
//                 [
//                     'days' => 180,
//                     'user_data' => $userData
//                 ]
//             );

//             if ($response->successful()) {

//                 $predictions = $response->json();

//                 HasilPrediksi::where('user_id', Auth::id())->delete();

//                 foreach ($predictions as $p) {

//                     HasilPrediksi::create([
//                         'user_id'     => Auth::id(),
//                         'tanggal'     => $p['ds'],
//                         'estimasi'    => (int) $p['yhat'],
//                         'batas_atas'  => (int) $p['yhat_upper'],
//                         'batas_bawah' => (int) $p['yhat_lower'],
//                     ]);
//                 }

//                 Session::forget('prediction_ready');

//                 return response()->json([
//                     'success' => true
//                 ]);
//             }

//             return response()->json([
//                 'error' => 'Gagal menghubungi server Flask.'
//             ], 500);

//         } catch (\Exception $e) {

//             return response()->json([
//                 'error' => $e->getMessage()
//             ], 500);
//         }
//     }
// }


namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use App\Models\DataPenjualan;
use App\Models\HasilPrediksi;
use Carbon\Carbon;

class PrediksiControllers extends Controller
{
    public function index()
    {
        $count = DataPenjualan::where('user_id', Auth::id())->count();

        $is_verified = $count >= 365;

        $prediction_ready = $this->checkPredictionStatus();

        $hasilPrediksi = HasilPrediksi::where('user_id', Auth::id())
            ->orderBy('tanggal', 'asc')
            ->get();

        return view('user.prediksi.index', compact(
            'is_verified',
            'count',
            'hasilPrediksi',
            'prediction_ready'
        ));
    }

    private function checkPredictionStatus()
    {
        return Session::get('prediction_ready', false);
    }

    // fungsi cek ping
    public function checkFlaskStatus()
    {
        try {
            $flaskBaseUrl = env('FLASK_URL');
            
            // Mengirim request kosong/ringan ke server Flask dengan timeout cepat (5 detik)
            $response = Http::timeout(5)->get($flaskBaseUrl . "/predict");

            // Jika server terhubung
            if ($response->status() === 405 || $response->successful()) {
                return response()->json([
                    'status' => 'connected',
                    'message' => 'Server Prediksi Berhasil Terhubung'
                ]);
            }

            // Jika server merespon tapi status servernya crash (500, dll)
            return response()->json([
                'status' => 'error_response',
                'message' => 'Server Prediksi Ada tapi Gagal Dihubungi'
            ]);

        } catch (\Exception $e) {
            // Jika RTO atau host ngrok tidak ditemukan / offline
            return response()->json([
                'status' => 'not_found',
                'message' => 'Server Prediksi Tidak Ditemukan (Offline)'
            ]);
        }
    }

    public function getForecast()
    {
        try {

            $count = DataPenjualan::where('user_id', Auth::id())->count();

            if ($count < 365) {

                return response()->json([
                    'error' => 'Minimal data penjualan harus 365 hari.'
                ], 400);
            }

            if (!$this->checkPredictionStatus()) {

                return response()->json([
                    'error' => 'Ada data baru. Silakan klik tombol "Siapkan Prediksi" terlebih dahulu pada menu Master Data.'
                ], 400);
            }

            $userData = DataPenjualan::where('user_id', Auth::id())
                ->orderBy('tanggal', 'asc')
                ->get(['tanggal', 'jumlah'])
                ->map(fn($item) => [
                    'tanggal' => Carbon::parse($item->tanggal)->format('Y-m-d'),
                    'jumlah' => $item->jumlah
                ]);

            $flaskBaseUrl = env('FLASK_URL'); 

            $response = Http::timeout(200)->post(
                $flaskBaseUrl . "/predict",
                [
                    'days' => 180,
                    'user_data' => $userData
                ]
            );

            if ($response->successful()) {

                $predictions = $response->json();

                HasilPrediksi::where('user_id', Auth::id())->delete();

                foreach ($predictions as $p) {

                    HasilPrediksi::create([
                        'user_id'     => Auth::id(),
                        'tanggal'     => $p['ds'],
                        'estimasi'    => (int) $p['yhat'],
                        'batas_atas'  => (int) $p['yhat_upper'],
                        'batas_bawah' => (int) $p['yhat_lower'],
                    ]);
                }

                Session::forget('prediction_ready');

                return response()->json([
                    'success' => true
                ]);
            }

            return response()->json([
                'error' => 'Gagal menghubungi server Flask. Pastikan URL Flask sudah benar dan server Flask sedang berjalan.'
            ], 500);

        } catch (\Exception $e) {
            
            return response()->json([
                'error' => 'Server Flask tidak dapat ditemukan.'
            ], 500);
        }
    }
}