<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\JenisKainModel;
use CodeIgniter\HTTP\ResponseInterface;

class TypeOfFabricController extends BaseController
{
    protected $typeOfFabrics;

    public function __construct()
    {
        $this->typeOfFabrics = new JenisKainModel();
    }

    public function index()
    {
        $data['title'] = 'Jenis Kain';
        $data['data'] = $this->typeOfFabrics->orderBy('created_at', 'desc')->findAll();
        return view('type_of_fabrics/index', $data);
    }

    public function create()
    {
        helper(['form']);
        $request = $this->request;
        if ($this->request->getMethod() == 'POST') {
            // Aturan validasi
            $rules = [
                'nama_jenis_kain'  => 'required|max_length[255]',
                'warna'          => 'required|max_length[255]',
                'harga_per_meter'          => 'required|max_length[255]|numeric',
                'foto_jenis_kain'             => 'uploaded[image]|max_size[photo,2048]|is_image[photo]|mime_in[photo,image/jpeg,image/png,image/gif]|permit_empty',
            ];

            $typeOfFabrics = $this->typeOfFabrics->orderBy('created_at', 'desc')->findAll();
            if (!$this->validate($rules)) {
                return view('type_of_fabrics/index', [
                    'title'      => 'Jenis Kain',
                    'data'       => $typeOfFabrics,
                    'validation' =>  $this->validator
                ]);
            }

            $image = null;
            if ($request->getFile('foto_jenis_kain') && $request->getFile('foto_jenis_kain')->isValid()) {
                $file = $request->getFile('foto_jenis_kain');
                $destinationPath = FCPATH . 'assets/jenis_kain/';
                $newFileName = rand() . '.' . $file->getClientExtension();
                $file->move($destinationPath, $newFileName);
                $image = 'assets/jenis_kain/' . $newFileName;
            }

            $result  = $this->typeOfFabrics->insert([
                'nama_jenis_kain' => $this->request->getPost('nama_jenis_kain'),
                'warna' => $this->request->getPost('warna'),
                'harga_per_meter'    => $this->request->getPost('harga_per_meter'),
                'foto_jenis_kain' => $image,
            ]);

            if ($result) {
                session()->setFlashdata('success', 'Data Jenis Kain Berhasil Ditambahkan');
                return redirect()->to('/type_of_fabrics');
            }

            session()->setFlashdata('error', 'Terjadi kesalahan, coba lagi.');
            return redirect()->to('/type_of_fabrics');
        }

        return view('type_of_fabrics/create', ['title' => 'Tambah Jenis Kain']);
    }

    public function edit($id)
    {
        helper(['form']);
        $request = $this->request;

        if ($this->request->getMethod() == 'POST') {
            $rules = [
                'nama_jenis_kain'          => 'required|max_length[255]',
                'warna'          => 'required|max_length[255]',
                'harga_per_meter'          => 'required|max_length[255]|numeric',
                'foto_jenis_kain'             => 'uploaded[image]|max_size[photo,2048]|is_image[photo]|mime_in[photo,image/jpeg,image/png,image/gif]|permit_empty',
            ];

            $typeOfFabrics = $this->typeOfFabrics->find($id);
            if (!$this->validate($rules)) {
                return view('type_of_fabrics/edit', [
                    'title'      => 'Edit Jenis Kain',
                    'data'       => $typeOfFabrics,
                    'validation' =>  $this->validator
                ]);
            }

            if (!$typeOfFabrics) {
                return redirect()->to('/product')->with('error', 'Data tidak ditemukan');
            }

            $dataUpdate = [
                'nama_jenis_kain' => $this->request->getPost('nama_jenis_kain'),
                'warna' => $this->request->getPost('warna'),
                'harga_per_meter'    => $this->request->getPost('harga_per_meter'),
            ];
            if ($request->getFile('foto_jenis_kain') && $request->getFile('foto_jenis_kain')->isValid()) {
                $file = $request->getFile('foto_jenis_kain');
                $destinationPath = FCPATH . 'assets/jenis_kain/';
                // Hapus foto lama jika ada
                if ($typeOfFabrics->foto_jenis_kain && file_exists(FCPATH . $typeOfFabrics->foto_jenis_kain)) {
                    unlink(FCPATH . $typeOfFabrics->foto_jenis_kain);
                }
                // Simpan foto baru
                $newFileName = rand() . '.' . $file->getClientExtension();
                $file->move($destinationPath, $newFileName);
                $dataUpdate['foto_jenis_kain'] = 'assets/jenis_kain/' . $newFileName;
            }
            $this->typeOfFabrics->update($id, $dataUpdate);

            return redirect()->to('type_of_fabrics/edit/' . $id)->with('success', 'Edit Jenis Kain Berhasil');
        }

        $data['title'] = 'Edit Jenis Kain';
        $data['data'] = $this->typeOfFabrics->find($id);
        return view('type_of_fabrics/edit', $data);
    }

    // DELETE: Menghapus data
    public function delete($id)
    {
        $data = $this->typeOfFabrics->find($id);
        if (!$data) {
            return redirect()->to('/jenis_kain')->with('error', 'Data tidak ditemukan');
        }

        if ($data->foto_jenis_kain && file_exists(FCPATH . $data->foto_jenis_kain)) {
            unlink(FCPATH . $data->foto_jenis_kain);
        }

        $this->typeOfFabrics->delete($id);
        return redirect()->to('/type_of_fabrics')->with('success', 'Data Jenis Kain berhasil dihapus.');
    }
}
