<?php

namespace App\Controllers;

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

class ModelController extends BaseController
{
    protected $Model;

    public function __construct()
    {
        $this->Model = new ModelCustomModel();
    }

    public function index()
    {
        $data['title'] = 'Model';

        $data['data'] = $this->Model->orderBy('created_at', 'desc')->findAll();
        if (auth()->user()->role == 'customer'):
            return view('model/index_customer', $data);
        else:
            return view('model/index', $data);
        endif;
    }

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

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

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

            $data = [
                'nama_model' => $this->request->getPost('nama_model'),
                'ongkos_pengerjaan' => $this->request->getPost('ongkos_pengerjaan'),
                'foto_model' => $image,
            ];

            // Insert data utama
            $this->Model->insert($data);

            session()->setFlashdata('success', 'Data Model Berhasil Ditambahkan');
            return redirect()->to('/model');
        }

        $data['title'] = 'Tambah Model';
        return view('model/create', $data);
    }

    public function edit($id)
    {
        helper(['form']);
        $request = $this->request;
        if ($this->request->getMethod() == 'POST') {
            $rules = [
                'nama_model' => 'required',
                'ongkos_pengerjaan' => 'required|numeric',
                'foto_model' => 'uploaded[image]|max_size[photo,2048]|is_image[photo]|mime_in[photo,image/jpeg,image/png,image/gif]|permit_empty',
            ];

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

            $existingData = $this->Model->find($id);
            if (!$existingData) {
                return redirect()->to('/product')->with('error', 'Data tidak ditemukan');
            }

            $dataUpdate = [
                'nama_model' => $this->request->getPost('nama_model'),
                'ongkos_pengerjaan' => $this->request->getPost('ongkos_pengerjaan')
            ];


            if ($request->getFile('foto_model') && $request->getFile('foto_model')->isValid()) {
                $file = $request->getFile('foto_model');
                $destinationPath = FCPATH . 'assets/model/';
                // Hapus foto lama jika ada
                if ($existingData->foto_model && file_exists(FCPATH . $existingData->foto_model)) {
                    unlink(FCPATH . $existingData->foto_model);
                }
                // Simpan foto baru
                $newFileName = rand() . '.' . $file->getClientExtension();
                $file->move($destinationPath, $newFileName);
                $dataUpdate['foto_model'] = 'assets/model/' . $newFileName;
            }
            $this->Model->update($id, $dataUpdate);

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

        $data['title'] = 'Edit Model';
        $data['data'] = $this->Model->find($id);
        return view('model/edit', $data);
    }

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

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

        // Hapus data utama
        $this->Model->delete($id);

        return redirect()->to('/model')->with('success', 'Data Model berhasil dihapus.');
    }

    public function detail($id)
    {
        $data['title'] = 'Detail Model';
        $data['data'] = $this->Model->find($id);
        return view('model/detail', $data);
    }
}
