<?php

namespace App\Controllers\Master;

use App\Controllers\BaseController;
use App\Models\Master\MarketplaceModel;
use App\Models\Master\ProdukModel;
use App\Models\Master\HargaMarketplaceModel;

class Marketplace extends BaseController
{
    protected $marketplaceModel;
    protected $produkModel;
    protected $hargaMarketplaceModel;

    public function __construct()
    {
        $this->marketplaceModel      = new MarketplaceModel();
        $this->produkModel           = new ProdukModel();
        $this->hargaMarketplaceModel = new HargaMarketplaceModel();
    }

    public function index()
    {
        $marketplaces = $this->marketplaceModel
                             ->orderBy('created_at', 'DESC')
                             ->findAll();

        // Lampirkan daftar harga produk ke setiap marketplace
        foreach ($marketplaces as &$m) {
            $m['harga_produk'] = $this->hargaMarketplaceModel
                ->getByMarketplace((int) $m['id_marketplace']);
        }
        unset($m);

        return view('master/marketplace/index', [
            'title'        => 'Master Marketplace',
            'marketplaces' => $marketplaces,
            'produk'       => $this->produkModel->findAll(),
        ]);
    }

    public function store()
    {
        $id = $this->request->getPost('id_marketplace');

        if (! $this->validate(['nama_marketplace' => 'required|min_length[2]|max_length[100]'])) {
            return redirect()->back()
                ->withInput()
                ->with('error', implode('<br>', $this->validator->getErrors()));
        }

        $data = [
            'nama_marketplace'    => $this->request->getPost('nama_marketplace'),
            'kontak_marketplace'  => $this->request->getPost('kontak_marketplace'),
            'catatan_marketplace' => $this->request->getPost('catatan_marketplace'),
            'status_marketplace'  => 'Aktif',
        ];

        if ($id) {
            $this->marketplaceModel->update($id, $data);
            $id_marketplace = (int) $id;
            $msg = 'Marketplace berhasil diperbarui!';
        } else {
            $this->marketplaceModel->insert($data);
            $id_marketplace = (int) $this->marketplaceModel->insertID();
            $msg = 'Marketplace berhasil ditambahkan!';
        }

        // --- Simpan harga + komisi per produk ---
        // Format POST: produk[id_produk][harga] dan produk[id_produk][komisi]
        $produkPost = $this->request->getPost('produk');

        // Kumpulkan id produk yang dikirim (yang dicentang)
        $idProdukDikirim = [];

        if (is_array($produkPost)) {
            foreach ($produkPost as $id_produk => $val) {
                $harga  = (isset($val['harga'])  && $val['harga']  !== '') ? (float) $val['harga']  : null;
                $komisi = (isset($val['komisi']) && $val['komisi'] !== '') ? (float) $val['komisi'] : 0;

                if ($harga === null) {
                    continue;
                }

                $idProdukDikirim[] = (int) $id_produk;

                $cek = $this->hargaMarketplaceModel
                    ->where('id_marketplace', $id_marketplace)
                    ->where('id_produk', $id_produk)
                    ->first();

                if ($cek) {
                    $this->hargaMarketplaceModel->update($cek['id_harga_marketplace'], [
                        'harga_marketplace' => $harga,
                        'komisi_produk'     => $komisi,
                    ]);
                } else {
                    $this->hargaMarketplaceModel->insert([
                        'id_marketplace'    => $id_marketplace,
                        'id_produk'         => $id_produk,
                        'harga_marketplace' => $harga,
                        'komisi_produk'     => $komisi,
                    ]);
                }
            }
        }

        // Hapus produk yang di-uncheck saat edit
        if ($id) {
            $existing = $this->hargaMarketplaceModel
                ->where('id_marketplace', $id_marketplace)
                ->findAll();

            foreach ($existing as $ex) {
                if (! in_array((int) $ex['id_produk'], $idProdukDikirim)) {
                    $this->hargaMarketplaceModel->delete($ex['id_harga_marketplace']);
                }
            }
        }

        return redirect()->to('/master/marketplace')->with('success', $msg);
    }

    public function toggleStatus($id)
    {
        $mp = $this->marketplaceModel->find($id);

        if ($mp) {
            $newStatus = ($mp['status_marketplace'] === 'Aktif') ? 'Non-Aktif' : 'Aktif';
            $this->marketplaceModel->update($id, ['status_marketplace' => $newStatus]);
            return redirect()->to('/master/marketplace')->with('success', 'Status berhasil diubah!');
        }

        return redirect()->to('/master/marketplace')->with('error', 'Data tidak ditemukan!');
    }

    public function delete($id)
    {
        $mp = $this->marketplaceModel->find($id);

        if ($mp) {
            $this->hargaMarketplaceModel->where('id_marketplace', $id)->delete();
            $this->marketplaceModel->delete($id);
            return redirect()->to('/master/marketplace')->with('success', 'Marketplace berhasil dihapus!');
        }

        return redirect()->to('/master/marketplace')->with('error', 'Data tidak ditemukan!');
    }
}