<?php 

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

require_once APPPATH . "core/My_Admin.php";

class Store extends My_Admin{
    public function __construct(){
        parent::__construct();
    }


    public $table = 'store';


    // * stores list
    public function index(){

        $this->load->view('admin/includes/header');
        $this->load->view('admin/store/view');
        $this->load->view('admin/includes/footer');
    }


    // * crete new entry
    public function create(){
        if($this->input->post()){

            $data = $_POST;

            $data['created_at'] = date('Y-m-d H:i:s');

            $this->cm->save_data($data);
            $this->session->set_flashdata('success', 'Credit data created successfuly.');
            redirect(site_url('/admin/store'));
        }

        $this->load->view('admin/includes/header');
        $this->load->view('admin/store/create');
        $this->load->view('admin/includes/footer');
    }


    //  * get store credit list 
    public function get_store_credit_list(){
       
        $datas = $this->store_model->get_data_table(['remove' => '0']);

        $final = [];
        $sno = $_POST['start'];
        foreach ($datas as $data) {
            $row = [];

            $row[] = ++$sno;
            $row[] = $data['credits'];
            $row[] = $data['price'];
            $row[] = $data['discount'];
            $row[] = "<div class='btn-group' role='group' aria-label='Basic example'>
                        <button type='button' class='btn btn-primary btn-sm' onclick='delete_credit(". $data['id']. ")' ><i class='fa-solid fa-trash'></i></button>
                    </div>";

            $final[] = $row;
        }

        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->store_model->count_all_data(['remove' => '0']),
            "recordsFiltered" => $this->store_model->count_filtered_data(['remove' => '0']),
            "data" => $final,
        );

        $this->output->set_content_type('application/json')->set_output(json_encode($output));

    }


    // * delete credit entry
    public function delete_credit(){
        request_method('DELETE');

        $request = check_get_parameter([
            'credit_id' => true
        ]);

        $data['remove'] = '1';

        $upd = $this->cm->update_where($data, ['id' => $request['credit_id']]);

        if($upd){
            echo json_encode([
                'status' => '1',
                'message' => 'Entry Deleted'
            ]);exit;

        }else{
            echo json_encode([
                'status' => '0',
                'message' => 'Error! try again'
            ]);exit;
        }
    }

}