<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Onsale extends Controller {

    public function action_index()
    {
        if(Auth::instance()->get_user()){
            
            $sale_model         = Model::factory('sale');
            $sales              = $sale_model->getMySale();
            $data               = array(
                                      'sales'   => $sales
                                      );
            
            $view = View::factory("mysale", $data);
            $this->request->response = $view;
        }
    }
    
    public function action_sold()
    {
        if(Auth::instance()->get_user()){
            if($_POST){
                
                $sale_model         = Model::factory('sale');
                    
                    if(isset($_POST["sales"]))
                        $sales              = $sale_model->setSold($_POST["sales"]);
                    else
                        $sales              = $sale_model->setDefault();
                        
                $data               = array('sales'   => $sales);
                
                $view = View::factory("mysale", $data);
                $this->request->response = $view;
            }
        }
    }
    
    public function action_delete($sale_id, $user_id){
        
        if($me = Auth::instance()->get_user()){
            
            if($me->id == $user_id){
                
                $sale_model = Model::factory('sale');
                $sale_model->deleteProduct($sale_id);
                
                $sales      = $sale_model->getMySale();
                $data       = array('sales'   => $sales);
                
                $view = View::factory("mysale", $data);
                $this->request->response = $view;
            }
        }
    }
    
    public function action_edit($sale_id, $user_id){
        
        if($me = Auth::instance()->get_user()){
            
            $category_model = Model::factory('category');
            $categories_arr = $category_model->getCategories();
            
            $sale_model = Model::factory('sale');
            $sale       = $sale_model->getSale($sale_id);
            
            if($_POST){
                if($me->id == $user_id){
                    $sale_model->editSale($sale_id, $_POST);
                    Request::instance()->redirect("main/act");
                }
            }
                
            $data = array("categories_arr"  => $categories_arr,
                          'sale'            => $sale);
            $view = View::factory("edit",$data);
            $this->request->response = $view;
        }
    }
}