<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\DataPenjualan;
use App\Imports\DataPenjualanImport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Maatwebsite\Excel\Facades\Excel;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class MasterDataControllers extends Controller
{
    public function index()
    {
        \Carbon\Carbon::setLocale('id');
        
        $user_id = Auth::id();

        $data_per_bulan = DataPenjualan::where('user_id', $user_id)
            ->select(
                DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan_tahun"),
                DB::raw("SUM(jumlah) as total_jumlah"),
                DB::raw("COUNT(tanggal) as jumlah_hari")
            )
            ->groupBy('bulan_tahun')
            ->orderBy('bulan_tahun', 'desc')
            ->get();

        $data_penjualan = DataPenjualan::where('user_id', $user_id)
            ->orderBy('tanggal', 'desc')
            ->get();

        $last_data = DataPenjualan::where('user_id', $user_id)
            ->orderBy('tanggal', 'desc')
            ->first();

        return view('user.masterdata.index', compact('data_per_bulan', 'data_penjualan', 'last_data'));
    }

    public function updateMassal(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'jumlah' => 'required|array'
        ]);

        $updatedDates = [];
        foreach ($request->ids as $key => $id) {
            $data = DataPenjualan::where('id', $id)->where('user_id', Auth::id())->first();
            if ($data && $data->jumlah != $request->jumlah[$key]) {
                $data->update(['jumlah' => $request->jumlah[$key]]);
                $updatedDates[] = Carbon::parse($data->tanggal)->translatedFormat('d F Y');
            }
        }

        Session::forget('prediction_ready');
        
        if (count($updatedDates) > 0) {
            return redirect()->back()->with('success', 'Data berhasil diperbarui.');
        }

        return redirect()->back()->with('info', 'Tidak ada perubahan data.');
    }

    public function destroyBulan(string $bulan_tahun)
    {
        DataPenjualan::where('user_id', Auth::id())
            ->where(DB::raw("DATE_FORMAT(tanggal, '%Y-%m')"), $bulan_tahun)
            ->delete();

        Session::forget('prediction_ready');
        return redirect()->back()->with('success', "Data bulan tersebut berhasil dihapus.");
    }

    // Perbaikan Backend: Penanganan validasi wajib isi dan konversi otomatis nilai kosong ke angka 0
    public function storeBulan(Request $request) 
    {
        // Memastikan array tanggal dan jumlah wajib dikirimkan oleh sistem
        $request->validate([
            'tanggal' => 'required|array', 
            'jumlah' => 'required|array'
        ]);
        
        $user_id = Auth::id();
        $dataToInsert = [];
        
        foreach ($request->tanggal as $key => $tgl) {
            $jml = $request->jumlah[$key];
            
            // ATURAN VALIDASI AMAN: Jika kolom tidak diisi atau kosong, paksa isi dengan angka 0
            if ($jml === null || $jml === '') {
                $jml = 0;
            }

            // Validasi jaminan anti-duplikat transaksi pada tanggal yang sama untuk pangkalan terkait
            $exists = DataPenjualan::where('user_id', $user_id)->where('tanggal', $tgl)->exists();
            if (!$exists) {
                $dataToInsert[] = [
                    'user_id'    => $user_id, 
                    'tanggal'    => $tgl, 
                    'jumlah'     => $jml,
                    'created_at' => now(), 
                    'updated_at' => now(),
                ];
            }
        }

        if (count($dataToInsert) > 0) {
            DataPenjualan::insert($dataToInsert);
            // Membersihkan session verifikasi prediksi agar data baru dihitung ulang
            Session::forget('prediction_ready');
            return redirect()->back()->with('success', "Seluruh baris data bulanan berhasil disimpan ke database.");
        }
        
        return redirect()->back()->with('error', 'Gagal memproses data. Baris tanggal untuk periode bulan terpilih sudah terdaftar di sistem.');
    }

    public function import(Request $request) {
        $request->validate(['file_excel' => 'required|mimes:xlsx,xls,csv|max:5120']);
        try {
            Excel::import(new DataPenjualanImport, $request->file('file_excel'));
            Session::forget('prediction_ready');
            return redirect()->back()->with('success', 'Import Berhasil!');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    public function siapkanPrediksi() {
        if (DataPenjualan::where('user_id', Auth::id())->count() < 365) {
            return redirect()->back()->with('error', 'Minimal data harus 365 hari.');
        }
        Session::put('prediction_ready', true);
        return redirect()->back()->with('success', 'Data diverifikasi.');
    }

    public function deleteAll() {
        DataPenjualan::where('user_id', Auth::id())->delete();
        Session::forget('prediction_ready');
        return redirect()->back()->with('success', 'Data dikosongkan.');
    }
}