<?php

class Stores {

	public static function getAll() {
		$response	=false;
		$sql		="SELECT * FROM `stores` ORDER BY `post_town` ASC ";
		$res		=mysql_query($sql) or die(mysql_error());
		if (mysql_num_rows($res)) {
			while ($row=mysql_fetch_assoc($res)) {
				$response[]=$row;
			}
		}
		return $response;
	}

	public static function getBySiteCode($site_code=false) {
		$response=false;
		if (false !== $site_code) {
			$sql="SELECT * FROM `stores` WHERE `site_code` = '".$site_code."' LIMIT 1 ";
			$res=mysql_query($sql) or die(mysql_error());
			if (mysql_num_rows($res)) {
				$row		=mysql_fetch_assoc($res);
				$response	=$row;

				$response['timing']=store_timing::getByStore($row['uid']);
			}
		}
		return $response;
	}

	public static function saveStores($arrStores=false) {
		$response=false;
		if (false !== $arrStores && count($arrStores) > 0) {
			#self::delete();
			$sql	="INSERT INTO `stores` (`site_code`,`car_park`,`tesco_site_code`,`address_line1`,`address_line2`,`post_town`,`post_code`,`county`,`when`) VALUES ";
			$values	='';
			foreach ($arrStores as $store) {
				#echo "<pre>";
				#print_r($store);
				if ($store['TescoSiteCode'] != 0) {
					$sitename=str_replace(" ".$store['TescoSiteCode'], "", $store['CarPark']);
					if (is_array($store['AddressLine2'])) {
						$arrdress2=((count($store['AddressLine2']) > 0) ? trim(implode(",", $store['AddressLine2'])) : '');
					} else {
						$arrdress2=$store['AddressLine2'];
					}
					$values.="('".(int) ($store['SiteCode'])."',"
					." '".mysql_real_escape_string(trim($sitename))."',"
					." '".mysql_real_escape_string($store['TescoSiteCode'])."',"
					." '".mysql_real_escape_string($store['AddressLine1'])."',"
					." '".mysql_real_escape_string($arrdress2)."',"
					." '".mysql_real_escape_string($store['PostTown'])."',"
					." '".mysql_real_escape_string($store['PostCode'])."',"
					." '".mysql_real_escape_string($store['County'])."',"
					." '".date("Y-m-d H:i:s")."'),";
				}
			}
			if ('' !== $values) {
				$sql .= rtrim($values, ",");
				$res		=mysql_query($sql) or die(mysql_error());
				$response	=mysql_insert_id();
			}
		}
		return $response;
	}

	public static function delete() {
		$sql		="DELETE FROM `stores`";
		$response	=mysql_query($sql) or die(mysql_error());
		return $response;
	}

}

?>