<?php

namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\PaketMenuModel;

class Menu extends ResourceController
{
    use ResponseTrait;

    protected $helpers = ['url'];

    // --- 1. UNTUK PELANGGAN ---
    public function index()
    {
        $menuModel = new PaketMenuModel();
        $dataMenu = $menuModel->where('status_aktif', 1)->findAll();

        if ($dataMenu) {
            foreach ($dataMenu as &$menu) {
                $menu['harga'] = (int) $menu['harga'];
                // Pastikan url_foto mengambil data nama file dari database
                $menu['url_foto'] = base_url('uploads/menu/' . $menu['url_foto']);
            }

            return $this->respond([
                'status'  => 200,
                'error'   => false,
                'message' => 'Data menu berhasil diambil',
                'data'    => $dataMenu
            ], 200);
        } else {
            return $this->failNotFound('Belum ada paket menu yang tersedia.');
        }
    }

    // --- 2. UNTUK ADMIN ---
    public function admin_index()
    {
        $menuModel = new PaketMenuModel();
        $dataMenu = $menuModel->findAll();

        foreach ($dataMenu as &$menu) {
            $menu['harga'] = (int) $menu['harga'];
            $menu['url_foto'] = base_url('uploads/menu/' . $menu['url_foto']);
        }

        return $this->respond([
            'status' => 200,
            'error'  => false,
            'data'   => $dataMenu
        ], 200);
    }

    // --- 3. ADMIN: TAMBAH MENU (DENGAN VALIDASI EKSTENSI) ---
    public function create()
    {
        $menuModel = new PaketMenuModel();
        
        // Validasi agar hanya file gambar yang boleh masuk
        $validationRule = [
            'foto' => [
                'label' => 'Image File',
                'rules' => 'uploaded[foto]'
                    . '|is_image[foto]'
                    . '|mime_in[foto,image/jpg,image/jpeg,image/gif,image/png]'
                    . '|max_size[foto,2048]',
            ],
        ];

        if (!$this->validate($validationRule)) {
            return $this->fail($this->validator->getErrors());
        }

        $file = $this->request->getFile('foto');

        if ($file->isValid() && !$file->hasMoved()) {
            // Gunakan getRandomName() dan pastikan ekstensi terbawa
            $newName = $file->getRandomName();
            
            // Gunakan FCPATH agar file benar-benar masuk ke folder public/uploads/menu
            $file->move(FCPATH . 'uploads/menu', $newName);
        } else {
            return $this->fail('Gagal mengunggah foto.');
        }

        $data = [
            'nama_paket'   => $this->request->getVar('nama_paket'),
            'deskripsi'    => $this->request->getVar('deskripsi'),
            'harga'        => $this->request->getVar('harga'),
            'url_foto'     => $newName,
            'status_aktif' => 1
        ];

        if ($menuModel->insert($data)) {
            return $this->respondCreated([
                'status'  => 201, 
                'error'   => false, 
                'message' => 'Berhasil tambah menu'
            ]);
        }
        return $this->fail('Gagal simpan data ke database');
    }

    // --- 4. ADMIN: UPDATE MENU ---
    public function update($id = null)
    {
        $menuModel = new PaketMenuModel();
        $oldData = $menuModel->find($id);

        if (!$oldData) return $this->failNotFound('Menu tidak ditemukan.');

        $data = [
            'nama_paket' => $this->request->getVar('nama_paket'),
            'deskripsi'  => $this->request->getVar('deskripsi'),
            'harga'      => $this->request->getVar('harga'),
        ];

        $file = $this->request->getFile('foto');
        
        // Jika ada file baru yang diunggah
        if ($file && $file->isValid()) {
            // Hapus foto lama jika ada
            $pathFotoLama = FCPATH . 'uploads/menu/' . $oldData['url_foto'];
            if (!empty($oldData['url_foto']) && file_exists($pathFotoLama)) {
                unlink($pathFotoLama);
            }
            
            $newName = $file->getRandomName();
            $file->move(FCPATH . 'uploads/menu', $newName);
            $data['url_foto'] = $newName;
        }

        if ($menuModel->update($id, $data)) {
            return $this->respond([
                'status'  => 200,
                'error'   => false,
                'message' => 'Data menu berhasil diperbarui'
            ]);
        }

        return $this->fail('Gagal memperbarui data.');
    }

    // --- 5. ADMIN: HAPUS MENU ---
    public function delete($id = null)
    {
        $menuModel = new PaketMenuModel();
        $data = $menuModel->find($id);

        if ($data) {
            $pathFile = FCPATH . 'uploads/menu/' . $data['url_foto'];
            if (!empty($data['url_foto']) && file_exists($pathFile)) {
                unlink($pathFile);
            }

            if ($menuModel->delete($id)) {
                return $this->respondDeleted([
                    'status'  => 200,
                    'error'   => false,
                    'message' => 'Menu berhasil dihapus permanen'
                ]);
            }
        }

        return $this->failNotFound('Data tidak ditemukan.');
    }

    // --- 6. FUNGSI WILAYAH ---
    public function get_wilayah()
    {
        $db = \Config\Database::connect();
        $data = $db->table('wilayah_ongkir')->get()->getResult();

        return $this->respond([
            'status' => 200,
            'error'  => false,
            'data'   => $data
        ], 200);
    }
}