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

class Subscription extends CI_Controller {
	public $data = array();

	public function __construct (){
        parent::__construct();
        
        $this->data['page_name'] = "Subscription";

        /**
         * Loading Models
         */
        $this->load->model('student_model');
        $this->load->model('subscription_pack_model');
        $this->load->model('subscription_model');

        $this->data['students'] = $this->student_model->get();
		$this->data['subscription_packs'] = $this->subscription_pack_model->get();
    }

	
	public function index()
	{
		$this->data['subscriptions'] = $this->_getParsedSubscriptions($this->subscription_model->get());
		$this->load->view('subscription/index',$this->data);
	}

	public function create()
	{

		if(isset($_POST['create'])) {
			$this->form_validation->set_rules(array(
				array(
					'field' => 'student',
	                'label' => 'Student',
	                'rules' => 'required',
	                'errors' => array(
	                        'required' => 'Please select a %s.',
	                ),
				),
				array(
					'field' => 'subscription_pack',
	                'label' => 'Subscription Pack',
	                'rules' => 'required',
	                'errors' => array(
	                        'required' => 'Please select a %s.',
	                ),
				)
			));
		}

		if($this->form_validation->run()==TRUE){
			if($this->subscription_model->insert()){
				set_alert('success','Subscription created Successfully.');
				redirect('subscription');
			} else {
				set_alert('error','Error while creating Subscription.');
			}
		}

		if($this->input->post('student_id') != NULL) {
			$this->data['create_student'] = $this->student_model->get($this->input->post('student_id'));
		}		
		$this->load->view('subscription/create',$this->data);
	}

	public function edit()
	{

		$this->data['subscription'] = $this->subscription_model->get($this->input->post('edit_id'));
		$this->load->view('subscription/edit',$this->data);
	}

	public function update()
	{
		if($this->subscription_model->update()) {
			set_alert('success','Subscription Updated Successfully');
		} else {
			set_alert('error', 'Error while updating subscription.');
		}
		redirect(base_url('subscription'));
	}


	protected function _getParsedSubscriptions($all_subscriptions)
	{
		$subscription_data = array();

		foreach($this->data['students'] as $key=>$student) {
			$subscription_data[$key] = array();
			foreach($all_subscriptions as $subscription) {
				if($subscription['parent']->user_ID==$student->user_ID){
					array_push($subscription_data[$key], $subscription);
				}
			}
		}
		return $subscription_data;
	}
}