<?php

namespace App\Controllers\Master;

use App\Controllers\BaseController;
use App\Models\Master\ResellerModel;
use App\Models\ProdukModel;

class Reseller extends BaseController
{
    protected $resellerModel;
    protected $productModel;

    public function __construct()
    {
        $this->resellerModel = new ResellerModel();
        $this->productModel  = new ProdukModel();
    }

    public function index()
    {
        $resellers   = $this->resellerModel->orderBy('created_at', 'DESC')->findAll();
        $allProducts = $this->productModel->getProdukAktif();

        $productMap = [];
        foreach ($allProducts as $p) {
            $productMap[$p['id_produk']] = $p['nama_produk'];
        }

        foreach ($resellers as &$r) {
            $ids = $r['id_produk_terkait_reseller']
                ? explode(',', $r['id_produk_terkait_reseller'])
                : [];
            $r['product_ids']    = $ids;
            $r['product_names']  = array_map(fn($id) => $productMap[$id] ?? 'Unknown', $ids);
            $r['harga_khusus']   = $this->resellerModel->getHargaKhusus((int)$r['id_reseller']);
        }

        return view('master/reseller/index', [
            'title'     => 'Master Reseller',
            'resellers' => $resellers,
            'products'  => $allProducts,
        ]);
    }

    public function store()
    {
        if (!$this->validate([
            'nama_reseller' => 'required|max_length[200]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $id          = $this->request->getPost('id_reseller');
        $product_ids = $this->request->getPost('product_ids') ?: [];
        $harga_list  = $this->request->getPost('harga_produk') ?: [];

        $data = [
            'nama_reseller'              => $this->request->getPost('nama_reseller'),
            'no_hp_reseller'             => $this->request->getPost('no_hp_reseller'),
            'alamat_reseller'            => $this->request->getPost('alamat_reseller'),
            'link_reseller'              => $this->request->getPost('link_reseller'),
            'status_reseller'            => 'Aktif',
            'id_produk_terkait_reseller' => !empty($product_ids) ? implode(',', $product_ids) : null,
        ];

        if ($id) {
            $this->resellerModel->update($id, $data);
            $savedId = $id;
            $msg = 'Data Reseller berhasil diperbarui!';
        } else {
            $this->resellerModel->insert($data);
            $savedId = $this->resellerModel->insertID();
            $msg = 'Reseller baru berhasil ditambahkan!';
        }

        // Simpan harga khusus per produk
        // harga_list format: ['id_produk' => 'harga', ...]
        $hargaPerProduk = [];
        foreach ($product_ids as $pid) {
            if (!empty($harga_list[$pid])) {
                $hargaPerProduk[$pid] = (float)$harga_list[$pid];
            }
        }
        $this->resellerModel->saveHargaKhusus((int)$savedId, $hargaPerProduk);

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

    public function toggleStatus($id)
    {
        $reseller = $this->resellerModel->find($id);
        if ($reseller) {
            $newStatus = ($reseller['status_reseller'] === 'Aktif') ? 'Non-Aktif' : 'Aktif';
            $this->resellerModel->update($id, ['status_reseller' => $newStatus]);
            return redirect()->to('/master/reseller')->with('success', 'Status berhasil diubah!');
        }
        return redirect()->to('/master/reseller')->with('error', 'Data tidak ditemukan!');
    }
}