<?php
###############################################################################
# Cookies.php
#
# @author Anil Kumar <akumar@codepunch.com>
# @link   https://codepunch.com
#
############################################################################### 

namespace 	CodePunch\Pro;
use 		CodePunch\Base\Util as UTIL;
use			CodePunch\Base\Text as TEXT;

###############################################################################

class Cookies  {
	
	private $authentication = null;
	
	###########################################################################
	
	public function __construct($auth=null) {
		$this->authentication = $auth;
	}


	public function save($sid, $url, $domain, $subdomain, $current_ts, $cookiefile) {
		if(!file_exists($cookiefile))
			return false;
		
		$auth = $this->authentication;
		$db = $auth->getDatabase();
		$handle = fopen($cookiefile, "r");
		if($handle) {
			$line = fgets($handle);
			$cookies = json_decode($line);
			$cookie_count = count($cookies);
			$session_cookie_count = 0;
			$persistent_cookie_count = 0;
			$cookiedata = array();
			foreach($cookies as $cookie) {
				$cookie = (array)$cookie;
				if(isset($cookie['session']) && intval($cookie['session']) == 1) {
					$session_cookie_count++;
					$type = 'session';
				}
				else {
					$persistent_cookie_count++;
					$type = 'persistent';
				}
				$expiry = intval($cookie['expires']);
				if($expiry <= 0)
					$expiry = NULL;
				else
					$expiry = date("Y-m-d H:i:s", $expiry);
				
				$thirdparty_cookie = '';
				$cookiedomain = $cookie['domain'];
				$cookiedomain = ($cookiedomain === "empty") ? "" : $cookiedomain;
				if(strlen($cookiedomain) && stripos($cookie['domain'], $domain) === false) {
					if(stripos($url, $cookiedomain) === false) {
						$thirdparty_cookie = $cookiedomain;
					}
				}
				$cv = substr($cookie['value'], 0, 2047);
				$c = array('sid'=>$sid, 'cookie_type'=>$type, 'auto_added'=>\CodePunch\LU\LookupManager::SD_COOKIE_ROWS,'cookie_name'=>$cookie['name'], 'cookie_value'=>substr($cookie['value'], 0, 2047), 'cookie_expiry'=>$expiry, 'cookie_domain'=>$cookie['domain'], 'cookie_thirdparty'=>$thirdparty_cookie, 'added_on'=>$current_ts, 'subdomain'=>$subdomain);
				$cookiedata[] = $c;
				$db->insertIntoTable($db->getSubdomainTableName(), $c);
			}
			UTIL::print($cookiedata);
			fclose($handle);
			return true;
		}
		return false;
	}
}
