<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Produk extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        if (!$this->session->userdata('login')) {
            redirect('auth');
        }
        $this->load->model('produk_model');
        $this->load->model('ulasan_model');
    }

    public function index()
    {
        $data['produk'] = $this->produk_model->get_all_produk()->result_array();
        foreach ($data['produk'] as $raw) {
            $id = $raw['id_produk'];
            $ratings[$id] = $this->ulasan_model->get_avg($id)->row_array();
            $rate_1 = $this->ulasan_model->get_rate($id, 1);
            $rate_2 = $this->ulasan_model->get_rate($id, 2);
            $rate_3 = $this->ulasan_model->get_rate($id, 3);
            $rate_4 = $this->ulasan_model->get_rate($id, 4);
            $rate_5 = $this->ulasan_model->get_rate($id, 5);
            $date['rate'] = array(
                'rate_1' => $rate_1,
                'rate_2' => $rate_2,
                'rate_3' => $rate_3,
                'rate_4' => $rate_4,
                'rate_5' => $rate_5,
            );
            $data['ulasan'] = $this->ulasan_model->get_ulasan($id)->result_array();
        } 
        $data['ratings'] = $ratings;
        $this->load->view('produk/index', $data);
    }

    public function hapus($id_produk = '')
    {
        $produk = $this->produk_model->get_produk($id_produk)->row_array();
        
        $file_name = $produk['gambar'];
        if (!empty($file_name)) {
            unlink('./assets/images/produk/' . $file_name);
        }
        
        $this->produk_model->delete_produk($produk['id_produk']);

        $this->session->set_flashdata('pesan', '<div class="alert alert-success" role="alert">Data berhasil dihapus</div>');

        redirect('produk');
    }
}
