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

class Store extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->require_login();
        $this->load->model('Store_model');
        $this->load->library('form_validation');
        $this->load->helper('form');
    }

    public function index() {
        $uid = $this->is_admin ? NULL : $this->auth_user->id;
        $data['stores'] = $this->Store_model->get_all($uid);
        $data['title']  = 'Data Toko';
        $this->render('store/index', $data);
    }

    public function create() {
        $data['title'] = 'Tambah Toko';
        $data['store'] = NULL;
        $this->render('store/form', $data);
    }

    public function store() {
        $this->form_validation->set_rules('name', 'Nama Toko', 'required|max_length[100]');
        if ($this->form_validation->run() === FALSE) {
            return $this->create();
        }
        $this->Store_model->insert([
            'user_id'     => $this->auth_user->id,
            'name'        => $this->input->post('name'),
            'address'     => $this->input->post('address'),
            'phone'       => $this->input->post('phone'),
            'footer_text' => $this->input->post('footer_text'),
        ]);
        $this->session->set_flashdata('success', 'Toko berhasil ditambahkan.');
        redirect('store');
    }

    public function edit($id) {
        $store = $this->Store_model->get($id);
        if (!$store || !$this->can_access($store->user_id)) show_404();
        $data['title'] = 'Edit Toko';
        $data['store'] = $store;
        $this->render('store/form', $data);
    }

    public function update($id) {
        $store = $this->Store_model->get($id);
        if (!$store || !$this->can_access($store->user_id)) show_404();
        $this->form_validation->set_rules('name', 'Nama Toko', 'required|max_length[100]');
        if ($this->form_validation->run() === FALSE) {
            return $this->edit($id);
        }
        $this->Store_model->update($id, [
            'name'        => $this->input->post('name'),
            'address'     => $this->input->post('address'),
            'phone'       => $this->input->post('phone'),
            'footer_text' => $this->input->post('footer_text'),
        ]);
        $this->session->set_flashdata('success', 'Toko berhasil diperbarui.');
        redirect('store');
    }

    public function delete($id) {
        $store = $this->Store_model->get($id);
        if (!$store || !$this->can_access($store->user_id)) show_404();
        $this->Store_model->delete($id);
        $this->session->set_flashdata('success', 'Toko berhasil dihapus.');
        redirect('store');
    }
}
