<?php

    //print_r($_POST);
    require_once "connection.php";
    session_start();
    $email_abonner = filter_var($_POST['email_abonner'],FILTER_VALIDATE_EMAIL);
    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        if(empty($email_abonner))
    	{
    		$msg_error = "Email Obligatoire";

    	}
        if(!isset($msg_error))
    	{
            //Check if Exist Email On Table Abonner
            $stmt = $con->prepare('SELECT * FROM `abonner` WHERE email=:email');
    		$stmt->bindParam(':email',$email_abonner);
            $stmt->execute();
            if($stmt->rowCount()>0)
    		{
                echo 'Email deja Exist';
            }
            else {
    			$stmt=$con->prepare('INSERT INTO `abonner`(`email`)
    				VALUES (:email)');
    			$stmt->bindParam(':email',$email_abonner);
    			$stmt->execute();
    			echo "Bien Ajouter";
            }
        }
        else
        {
    		echo "Error " . $msg_error;
    		exit();
    	}
         // MailChimp API credentials
         $apiKey = '676aa6b5a9aae02b8ba01480977a6662-us7';
         $listID = '42f4aa0351';

         // MailChimp API URL
        $memberID = md5(strtolower($email_abonner));
        $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
        $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;

        // member information
        $json = json_encode([
            'email_address' => $email_abonner,
            'status'        => 'subscribed'
        ]);


        // send a HTTP POST request with curl
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
    }


?>