<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Sale;
use App\Models\Channel;
use App\Models\Product;
use App\Models\User;
use App\Models\Notification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class SalesController extends Controller
{
    public function index() {
        $channels = Channel::all();
        $products = Product::groupedByKategori();
        $labelKategori = Product::labelKategori();
        $history = Sale::with('channel')->orderBy('id', 'desc')->get();
        $csNames = \App\Models\CsName::where('aktif', true)->orderBy('nama')->get();
        return view('input_penjualan', compact('channels', 'history', 'products', 'labelKategori', 'csNames'));
    }

    public function store(Request $request) {
        $request->validate([
            'tgl'        => 'required|date',
            'channel_id' => 'required',
            'nama_cs'    => 'required|string',
            'nominal_gmv'=> 'required|numeric',
        ]);

        $data = $request->except('_token', 'qty_produk');
        $data['admin_id'] = Auth::id();
        $data['status']   = 'pending';

        // Proses detail produk dari input dinamis
        $qtyProduk = $request->input('qty_produk', []);
        $detailProduk = [];
        $totalToples = 0; $totalMini = 0; $totalPouch = 0;
        $totalKue = 0; $totalCookies = 0;

        foreach ($qtyProduk as $kode => $qty) {
            if ((int)$qty > 0) {
                $produk = Product::where('kode', $kode)->first();
                if ($produk) {
                    // Hitung qty efektif untuk tier
                    $qtyEfektifToples = 0;
                    $qtyEfektifPouch  = 0;
                    foreach ($qtyProduk as $k => $q) {
                        if ((int)$q > 0) {
                            $p = Product::where('kode', $k)->first();
                            if ($p) {
                                if ($p->tipe_harga === 'toples') $qtyEfektifToples += (int)$q * $p->konversi_toples;
                                if ($p->tipe_harga === 'pouch')  $qtyEfektifPouch  += (int)$q;
                            }
                        }
                    }
                    $qtyEfektif = $produk->tipe_harga === 'pouch' ? $qtyEfektifPouch : $qtyEfektifToples;
                    $hargaEfektif = $produk->hitungHarga((int)$qtyEfektif);

                    $detailProduk[] = [
                        'kode'     => $kode,
                        'nama'     => $produk->nama,
                        'kategori' => $produk->kategori,
                        'harga'    => $hargaEfektif,
                        'qty'      => (int)$qty,
                        'subtotal' => $hargaEfektif * (int)$qty,
                    ];
                    // Akumulasi qty ringkasan
                    if (in_array($produk->kategori, ['TOPLES_REGULER'])) $totalToples += (int)$qty;
                    if (in_array($produk->kategori, ['TOPLES_MINI']))    $totalMini   += (int)$qty;
                    if (in_array($produk->kategori, ['POUCH']))          $totalPouch  += (int)$qty;
                    if (in_array($produk->kategori, ['KUE_KERANJANG']))  $totalKue    += (int)$qty;
                    if (in_array($produk->kategori, ['COOKIES']))        $totalCookies+= (int)$qty;
                }
            }
        }

        $data['detail_produk']    = json_encode($detailProduk);
        $data['qty_toples']       = $totalToples;
        $data['qty_mini']         = $totalMini;
        $data['qty_pouch']        = $totalPouch;
        $data['qty_kue_keranjang']= $totalKue;
        $data['qty_cookies']      = $totalCookies;

        // Grand total
        $biayaKirim = (int)str_replace('.', '', $request->biaya_kirim ?? 0);
        $nominalGmv = (int)str_replace('.', '', $request->nominal_gmv ?? 0);
        $data['biaya_kirim'] = $biayaKirim;
        $data['nominal_gmv'] = $nominalGmv;
        $data['grand_total'] = $nominalGmv + $biayaKirim;

        // Generate nomor invoice otomatis: LVS-001
        $last = Sale::whereNotNull('nomor_invoice')
                    ->orderBy('id', 'desc')
                    ->first();

        $nextNumber = 1;
        if ($last && $last->nomor_invoice) {
            $lastNumber = (int) substr($last->nomor_invoice, 4); // hilangkan "LVS-"
            $nextNumber = $lastNumber + 1;
        }

        $data['nomor_invoice'] = 'LVS-' . str_pad($nextNumber, 3, '0', STR_PAD_LEFT);
        $sale = Sale::create($data);

        // Notif ke Gudang — ada pesanan baru
        Notification::create([
            'for_role' => 'gudang',
            'judul'    => 'Pesanan Baru Masuk',
            'pesan'    => 'CS ' . $request->nama_cs . ' menginput pesanan baru dari ' . ($sale->channel->nama_channel ?? '-'),
            'icon'     => 'ti-shopping-cart',
            'warna'    => '#E8748A',
            'sale_id'  => $sale->id,
        ]);

        // Notif ke Admin — ada pesanan baru
        Notification::create([
            'for_role' => 'admin',
            'judul'    => 'Pesanan Baru Masuk',
            'pesan'    => 'CS ' . $request->nama_cs . ' menginput pesanan baru dari ' . ($sale->channel->nama_channel ?? '-'),
            'icon'     => 'ti-shopping-cart',
            'warna'    => '#E8748A',
            'sale_id'  => $sale->id,
        ]);

        return back()->with('success', 'Data ' . $request->nama_cs . ' berhasil disimpan!');
    }

    public function edit($id) {
        $sale = Sale::findOrFail($id);
        if ($sale->status !== 'pending') {
            return redirect('/input?tab=riwayat')->with('error', 'Gagal! Data sudah diproses oleh Gudang.');
        }
        $channels = Channel::all();
        $products = Product::groupedByKategori();
        $labelKategori = Product::labelKategori();
        return view('edit_penjualan', compact('sale', 'channels', 'products', 'labelKategori'));
    }

    public function update(Request $request, $id) {
        $request->validate([
            'tgl'        => 'required|date',
            'channel_id' => 'required',
            'nama_cs'    => 'required',
            'nominal_gmv'=> 'required|numeric',
        ]);

        $sale = Sale::findOrFail($id);
        $data = $request->except('_token', '_method', 'qty_produk');

        $qtyProduk = $request->input('qty_produk', []);
        $detailProduk = [];
        $totalToples = 0; $totalMini = 0; $totalPouch = 0;
        $totalKue = 0; $totalCookies = 0;

        foreach ($qtyProduk as $kode => $qty) {
    if ((int)$qty > 0) {
        $produk = Product::where('kode', $kode)->first();
        if ($produk) {
            // Hitung qty efektif untuk tier (sama seperti di store)
            $qtyEfektifToples = 0;
            $qtyEfektifPouch  = 0;
            foreach ($qtyProduk as $k => $q) {
                if ((int)$q > 0) {
                    $p = Product::where('kode', $k)->first();
                    if ($p) {
                        if ($p->tipe_harga === 'toples') $qtyEfektifToples += (int)$q * $p->konversi_toples;
                        if ($p->tipe_harga === 'pouch')  $qtyEfektifPouch  += (int)$q;
                    }
                }
            }
            $qtyEfektif   = $produk->tipe_harga === 'pouch' ? $qtyEfektifPouch : $qtyEfektifToples;
            $hargaEfektif = $produk->hitungHarga((int)$qtyEfektif);

            $detailProduk[] = [
                'kode'     => $kode,
                'nama'     => $produk->nama,
                'kategori' => $produk->kategori,
                'harga'    => $hargaEfektif,        // ✅
                'qty'      => (int)$qty,
                'subtotal' => $hargaEfektif * (int)$qty,  // ✅
            ];
                    if (in_array($produk->kategori, ['TOPLES_REGULER'])) $totalToples += (int)$qty;
                    if (in_array($produk->kategori, ['TOPLES_MINI']))    $totalMini   += (int)$qty;
                    if (in_array($produk->kategori, ['POUCH']))          $totalPouch  += (int)$qty;
                    if (in_array($produk->kategori, ['KUE_KERANJANG']))  $totalKue    += (int)$qty;
                    if (in_array($produk->kategori, ['COOKIES']))        $totalCookies+= (int)$qty;
                }
            }
        }

        $data['detail_produk']     = json_encode($detailProduk);
        $data['qty_toples']        = $totalToples;
        $data['qty_mini']          = $totalMini;
        $data['qty_pouch']         = $totalPouch;
        $data['qty_kue_keranjang'] = $totalKue;
        $data['qty_cookies']       = $totalCookies;

        $biayaKirim = (int)str_replace('.', '', $request->biaya_kirim ?? 0);
        $nominalGmv = (int)str_replace('.', '', $request->nominal_gmv ?? 0);
        $data['biaya_kirim'] = $biayaKirim;
        $data['nominal_gmv'] = $nominalGmv;
        $data['grand_total'] = $nominalGmv + $biayaKirim;

        $sale->update($data);
        return redirect('/input?tab=riwayat')->with('success', 'Data berhasil diperbarui!');
    }

    public function destroy($id) {
        $sale = Sale::findOrFail($id);
        if ($sale->status !== 'pending') {
            return redirect('/input?tab=riwayat')->with('error', 'Data tidak bisa dihapus karena sudah diproses.');
        }
        $sale->delete();
        return redirect('/input?tab=riwayat')->with('success', 'Data berhasil dihapus!');
    }

    public function dashboard() {
        $totalGmv  = Sale::where('status', '!=', 'dibatalkan')->sum('nominal_gmv') ?? 0;
        $mainData  = Sale::select('channel_id',
                DB::raw('SUM(qty_toples) as s_toples'),
                DB::raw('SUM(qty_mini) as s_mini'),
                DB::raw('SUM(qty_pouch) as s_pouch'),
                DB::raw('SUM(nominal_gmv) as s_gmv'))
            ->where('status', '!=', 'dibatalkan')->groupBy('channel_id')->with('channel')->orderBy('s_gmv','desc')->get();
        $individuData = Sale::select('nama_cs', DB::raw('SUM(nominal_gmv) as total_gmv'))
            ->where('status', '!=', 'dibatalkan')->whereNotNull('nama_cs')->groupBy('nama_cs')->orderBy('total_gmv','desc')->get();

        // Data untuk line chart — GMV per hari (30 hari terakhir)
        $gmvHarian = Sale::select(
                DB::raw('DATE(tgl) as tanggal'),
                DB::raw('SUM(nominal_gmv) as total')
            )
            ->where('status', '!=', 'dibatalkan')->whereRaw("tgl >= NOW() - INTERVAL '30 days'")
            ->groupBy(DB::raw('DATE(tgl)'))
            ->orderBy('tanggal')
            ->get()
            ->map(fn($r) => ['tgl' => $r->tanggal, 'total' => $r->total]);

        // Data untuk donut chart — GMV per channel
        $gmvChannel = $mainData->map(fn($r) => [
    'nama'  => $r->channel->nama_channel ?? 'Unknown',
    'total' => (float) $r->s_gmv,
    ])->values()->toArray();

        // Stat cards
        $totalTrx     = Sale::where('status', '!=', 'dibatalkan')->count();
        $totalChannel = Sale::where('status', '!=', 'dibatalkan')->distinct('channel_id')->count('channel_id');
        $totalCs      = Sale::where('status', '!=', 'dibatalkan')->whereNotNull('nama_cs')->distinct('nama_cs')->count('nama_cs');
        $bulanIni     = Sale::where('status', '!=', 'dibatalkan')->whereRaw("EXTRACT(MONTH FROM tgl) = ?", [date('m')])->sum('nominal_gmv');
        $pesananPending   = Sale::where('status', 'pending')->count();
        $pesananDikemas   = Sale::where('status', 'dikemas')->count();
        $pesananSiapKirim = Sale::where('status', 'siap_kirim')->count();

        return view('dashboard', compact(
            'totalGmv', 'mainData', 'individuData',
            'gmvHarian', 'gmvChannel',
            'totalTrx', 'totalChannel', 'totalCs', 'bulanIni',
            'pesananPending', 'pesananDikemas', 'pesananSiapKirim'
        ));
    }

    public function orderList() {
        $sales = Sale::with(['channel'])->orderBy('id','desc')->get();
        return view('gudang_index', compact('sales'));
    }

    public function updateStatus(Request $request) {
        $request->validate(['id'=>'required|exists:sales_daily,id','status'=>'required|in:pending,dikemas,siap_kirim,dikirim,selesai,dibatalkan']);
        $sale = Sale::find($request->id);
        $sale->status = $request->status;
        $sale->save();

        // Notif ke CS — status pesanan berubah
        $statusLabel = [
            'dikemas'    => 'sedang dikemas',
            'siap_kirim' => 'siap dikirim',
            'dikirim'    => 'sudah dikirim',
            'selesai'    => 'selesai',
            'dibatalkan' => 'dibatalkan',
            'pending'    => 'kembali ke pending',
        ][$request->status] ?? $request->status;

        $ikonMap = [
            'dikemas'    => 'ti-package',
            'siap_kirim' => 'ti-truck',
            'dikirim'    => 'ti-send',
            'selesai'    => 'ti-circle-check',
            'dibatalkan' => 'ti-x',
            'pending'    => 'ti-clock',
        ];

        Notification::create([
            'for_role' => 'cs',
            'judul'    => 'Status Pesanan Diperbarui',
            'pesan'    => 'Pesanan ' . ($sale->nama_pemesan ?? '#'.$sale->id) . ' ' . $statusLabel,
            'icon'     => $ikonMap[$request->status] ?? 'ti-bell',
            'warna'    => $request->status === 'selesai' ? '#16a34a' : ($request->status === 'dibatalkan' ? '#dc2626' : '#7B3F1E'),
            'sale_id'  => $sale->id,
        ]);

        // Notif ke Admin — status berubah
        Notification::create([
            'for_role' => 'admin',
            'judul'    => 'Status Pesanan Diperbarui',
            'pesan'    => 'Pesanan ' . ($sale->nama_pemesan ?? '#'.$sale->id) . ' ' . $statusLabel,
            'icon'     => $ikonMap[$request->status] ?? 'ti-bell',
            'warna'    => $request->status === 'selesai' ? '#16a34a' : ($request->status === 'dibatalkan' ? '#dc2626' : '#7B3F1E'),
            'sale_id'  => $sale->id,
        ]);

        return back()->with('success', 'Status pesanan berhasil diupdate!');
    }

    public function csLengkapi($id) {
        $sale = Sale::with('channel')->findOrFail($id);
        return view('cs_lengkapi', compact('sale'));
    }

    public function csLengkapiUpdate(Request $request, $id) {
        $sale = Sale::findOrFail($id);
        $sale->update([
            'nama_pemesan'     => $request->nama_pemesan,
            'no_telp_pemesan'  => $request->no_telp_pemesan,
            'nama_penerima'    => $request->nama_penerima,
            'no_telp_penerima' => $request->no_telp_penerima,
            'alamat'           => $request->alamat,
            'kelurahan'        => $request->kelurahan,
            'kecamatan'        => $request->kecamatan,
            'kota'             => $request->kota,
            'provinsi'         => $request->provinsi,
            'jasa_kirim'       => $request->jasa_kirim,
            'nama_transfer'    => $request->nama_transfer,
            'catatan'          => $request->catatan,
        ]);
        return redirect('/input')->with('success', 'Data pesanan berhasil dilengkapi!');
    }

    public function lengkapi($id) {
        $sale = Sale::findOrFail($id);
        $channels = Channel::all();
        return view('gudang_lengkapi', compact('sale', 'channels'));
    }

    public function lengkapiUpdate(Request $request, $id) {
        $sale = Sale::findOrFail($id);

        // Simpan nilai lama sebelum update
        $resiLama = $sale->nomor_resi;

        $updateData = [
            'nomor_resi'      => $request->nomor_resi,
            'jasa_kirim'      => $request->jasa_kirim,
            'nama_penerima'   => $request->nama_penerima,
            'no_telp_penerima'=> $request->no_telp_penerima,
            'alamat'          => $request->alamat,
            'kota'            => $request->kota,
            'provinsi'        => $request->provinsi,
            'catatan'         => $request->catatan,
        ];

        // Auto set status ke dikemas saat resi pertama kali diisi
        if ($request->nomor_resi && !$resiLama) {
            $updateData['status'] = 'dikemas';
        }

        $sale->update($updateData);

        // Kirim notif ke CS & Admin kalau resi baru diisi
        if ($request->nomor_resi && !$resiLama) {
            $pesanNotif = 'Resi pesanan ' . ($sale->nama_pemesan ?? '#'.$sale->id) . ' sudah diisi: ' . $request->nomor_resi;

            Notification::create([
                'for_role' => 'cs',
                'judul'    => 'Nomor Resi Diisi',
                'pesan'    => $pesanNotif,
                'icon'     => 'ti-truck-delivery',
                'warna'    => '#1d4ed8',
                'sale_id'  => $sale->id,
            ]);

            Notification::create([
                'for_role' => 'admin',
                'judul'    => 'Nomor Resi Diisi',
                'pesan'    => $pesanNotif,
                'icon'     => 'ti-truck-delivery',
                'warna'    => '#1d4ed8',
                'sale_id'  => $sale->id,
            ]);
        }

        return redirect('/pesanan')->with('success', 'Data pesanan berhasil dilengkapi!');
    }

    public function invoice($id) {
        $sale = Sale::with('channel')->findOrFail($id);
        $detailProduk = [];
        if ($sale->detail_produk) {
            $detailProduk = is_array($sale->detail_produk)
                ? $sale->detail_produk
                : json_decode($sale->detail_produk, true);
        }
        return view('invoice', compact('sale', 'detailProduk'));
    }

    public function suratJalan($id) {
        $sale = Sale::with('channel')->findOrFail($id);
        $detailProduk = [];
        if ($sale->detail_produk) {
            $detailProduk = is_array($sale->detail_produk)
                ? $sale->detail_produk
                : json_decode($sale->detail_produk, true);
        }
        return view('surat_jalan', compact('sale', 'detailProduk'));
    }
}