<?php

namespace App\Controllers\Master;

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

class Maklon extends BaseController
{
    protected $maklonModel;
    protected $productModel;

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

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

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

        foreach ($maklons as &$m) {
            $ids = $m['id_produk_terkait_maklon']
                ? explode(',', $m['id_produk_terkait_maklon'])
                : [];
            $m['product_ids']   = $ids;
            $m['product_names'] = array_map(fn($id) => $productMap[$id] ?? 'Unknown', $ids);
            $m['harga_khusus']  = $this->maklonModel->getHargaKhusus((int)$m['id_maklon']);
        }

        return view('master/maklon/index', [
            'title'    => 'Master Mitra Maklon',
            'maklons'  => $maklons,
            'products' => $allProducts,
        ]);
    }

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

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

        $data = [
            'nama_maklon'              => $this->request->getPost('nama_maklon'),
            'no_hp_maklon'             => $this->request->getPost('no_hp_maklon'),
            'alamat_maklon'            => $this->request->getPost('alamat_maklon'),
            'status_maklon'            => 'Aktif',
            'id_produk_terkait_maklon' => !empty($product_ids) ? implode(',', $product_ids) : null,
        ];

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

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

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

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