<?php
namespace src\models;
use \core\Model;
use \core\Database;

class Shipping_company extends Model {

	public static function saveShipping($shipping, $note) {
		$s = Shipping_company::insert($shipping)
		->execute();

		Shipping_company::insert(['id_shipping_company' => $s, 'note' => $note])
			->table('shipping_company_notes')
		->execute();
	}

	public static function updateShipping($shippingId, $shipping, $note) {
		Shipping_company::update($shipping)
			->where('id', $shippingId)
		->execute();

		Shipping_company::update(['note' => $note])
			->table('shipping_company_notes')
			->where('id_shipping_company', $shippingId)
		->execute();
	}

	public static function getAll() {
		$data = Shipping_company::select()
			->get();

		return $data;
	}

	public static function getShippings($offset, $limit, $filter) {
		$data = Shipping_company::select()
			->where($filter['f_others'], $filter['fs_others'], $filter['fo_value'])
			->where('status', $filter['fs_status'], $filter['f_status'])
			->orderBy(['status' => '!= 1', 'company_name' => 'asc'])
			->offset($offset)
			->limit($limit)
		->get();

		return $data;
	}

	public static function getName($shipping) {
		$data = Shipping_company::select('company_name')
			->where('id', $shipping)
		->one();

		return $data['company_name'];
	}

	public static function getShipping($shipping) {
		$data = Shipping_company::select()
			->where('id', $shipping)
		->one();

		$note = Shipping_company::select('note')
			->table('shipping_company_notes')
			->where('id_shipping_company', $shipping)
		->one();

		$data['note'] = $note['note'];
		return $data;
	}	

	public static function getCount($filter) {
		$c = Shipping_company::select()
			->where($filter['f_others'], $filter['fs_others'], $filter['fo_value'])
			->where('status', $filter['fs_status'], $filter['f_status'])
		->count();

		return $c;
	}

	public static function existsShipping($ref, $value) {
		$response = false;
		$c = Shipping_company::select('id')
            ->where($ref, $value)
        ->count();

        if($c > 0) {
            $response = true;
        }
        return $response;
	}

	public static function getBirthdays($dateInit, $dateEnd) {
		$data = array();		
		$db = Database::getInstance();

		$sql = $db->prepare("
			SELECT company_name as name, birth_date, status, first_phone, email, state, 
			(select citys.name from citys where citys.id = shipping_companys.city) as city
			FROM shipping_companys
			WHERE DATE_FORMAT(birth_date, '%m-%d') BETWEEN :d_ini AND :d_end			
			ORDER BY DATE_FORMAT(birth_date, '%m-%d') ASC
			");
		$sql->bindValue(':d_ini', date('m-d', strtotime($dateInit)));
		$sql->bindValue(':d_end', date('m-d', strtotime($dateEnd)));		
		$sql->execute();

		if($sql->rowCount() > 0) {
			$data = $sql->fetchAll(\PDO::FETCH_ASSOC);
		}

		return $data;
	}

}