<?php 

defined('BASEPATH') or exit ('Direct script access not allowed');

require_once APPPATH . "core/My_Admin.php";

class Discount extends My_Admin{

    public function __construct()
    {
        parent::__construct();
    }

    public $table = 'discounts';


    // * discount list
    public function index(){

        $data['details'] = $this->cm->search_multiple_where([], 'ASC','id', 'discounts');

        $this->load->view('admin/includes/header', $data);
        $this->load->view('admin/discounts/view');
        $this->load->view('admin/includes/footer');

    }


    // * create new discount 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', 'discount created successfuly.');
            redirect(site_url('/admin/discount'));
        }

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


    // * delete discount entry
    public function delete_discount() {
        request_method('POST');
    
        $discount_id = $this->input->get('discount_id');
    
        $del = $this->cm->delete_where(['id' => $discount_id], 'discounts');
    
        if ($del) {
            echo json_encode([
                'status' => '1',
                'message' => 'Discount deleted successfully.'
            ]);
            exit;
        }
    
        echo json_encode([
            'status' => '0',
            'message' => 'Failed to delete discount.'
        ]);
        exit;
    }
    

    // * update discount entry 
    public function update_discount() {
        request_method('POST');
    
        $request = check_parameter([
            'discount_id' => true,
        ]);
    
        $request['min_quantity'] = $this->input->post('min_quantity');
        $request['discount_percentage'] = $this->input->post('discount_percentage');
    
        $discount_id = $this->input->get('discount_id');
    
        $upd = $this->cm->update_where($request, ['id' => $discount_id], 'discounts');
    
        if ($upd) {
            echo json_encode([
                'status' => '1',
                'message' => 'Discount details updated successfully.'
            ]);
            exit;
        }
    
        echo json_encode([
            'status' => '0',
            'message' => 'Failed to update discount details.'
        ]);
        exit;
    }
    
    

}