<?php
require_once("simple_html_dom.php");
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<style type="text/css">
    /*form{
        visibility:hidden;
    }*/
</style>
<?php
$cid = (int)$_GET['cid'];
        global $wpdb;
        $table_name = $wpdb->prefix . "social_post_press";  
        if($cid <= 0 ){
            echo json_encode(array('error' => 'No campaign found'));
        }else{
            $query = sprintf('select * from '.$table_name.' where id = %d',$cid);
            $result = $wpdb->get_results($query);
            //print_r($result);
            // var_dump($result[0]->$social_post_press_optin_code);
            // var_dump($result[0]->$social_post_press_optin_form);
            $result[0]->social_post_press_optin_form = unserialize($result[0]->social_post_press_optin_form);
            //$result->awber_url='http://socialviralapps.com/wp/handle_aweber?cid='.$cid;
            $formdata= stripslashes($result[0]->social_post_press_optin_code);

            $html = new simple_html_dom();
            $html->load($formdata);

            $data=array();
            $actionurl='';

            foreach($html->find("form") as $input){
                $actionurl=$input->action;
            }

            foreach($html->find("input") as $input){
                //echo $input->name;die;
                $data[$input->name]=$input->value;
                foreach($_POST as $key=>$val){
                    if($input->name==$key){
                        $data[$key]=$val;
                        check_email($val);
                    }
                }
            }
            //print_r($data);
            submitform($data,$actionurl);
        }

function check_email($check) {
    $expression = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/";
    if (preg_match($expression, $check)) {
        global $wpdb;
        $table_name2 = $wpdb->prefix . "social_post_press_emaildatabase";
        $default_values = array('email' =>$check);
        $wpdb->insert($table_name2,$default_values);   
    } else {
        
    } 
}

function submitform($fields,$action){

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

    $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $action);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST,count($fields));

curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
echo $output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
}
?>

<script type="text/javascript">
	//jQuery(document).ready(function(){
		<?php
			//foreach($_POST as $key=>$val){
				?>
					//jQuery("input[name=<?php echo stripslashes($key); ?>]").attr("value","<?php echo stripslashes($val); ?>");
				<?php
			//}
		//?>
		//jQuery("form").attr("target","");
        //jQuery("form input[name=submit]").remove();
		//jQuery("form").submit();		
	//});
</script>