<?php
include "../root.class.php";
$authorisation = new authentication();
$db = new db_safeguard();

$res = $db->query("cpanel", "SELECT * FROM cpanel WHERE record_id = {$_POST['cpanel_id']}");

if ($res->num_rows > 0) {
    $row = $res->fetch_assoc();
    $cpanel_user = $row['username'];
    $cpanel_pass = $row['password'];
    $cpanel_pass = $authorisation->decrypt_password($cpanel_pass);
    $domain = $row['domain'];
    $link = $row['login_address'];

} else {
    echo 0;
    exit();
}
// API URL to list email accounts
$url = $link . "/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_module=Email&cpanel_jsonapi_func=listpops&domain=" . urlencode($domain);

// cPanel authentication
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERPWD, "$cpanel_user:$cpanel_pass");

// Execute request
$response = curl_exec($ch);
curl_close($ch);

// Decode response
$result = json_decode($response, true);

// Output results
if (isset($result['cpanelresult']['data'])) {
    echo "<h3>Email Accounts FOUND:</h3><ul>";
    foreach ($result['cpanelresult']['data'] as $email) {
        echo "<li>" . htmlspecialchars($email['email']) . "</li>";
        $email_check_res = $db->query("emails", "SELECT * FROM emails WHERE email = '{$email['email']}' AND client_id = '{$_SESSION['selected_client']}' AND email_server_id = '{$_POST['server_id']}'");
        if ($email_check_res->num_rows < 1) {
            $password = $authorisation->encrypt_password("");
            $db->query("emails", "INSERT INTO `emails`(`email_server_id`, `client_id`, `email`, `password`, `active_protection`, `monthly_password_change`, `webmail_link`) VALUES ('{$_POST['server_id']}','{$_SESSION['selected_client']}','{$email['email']}','$password',0,0,'https://reseller141.aserv.co.za:2096')");
            echo "<li> ADDED </li>";
        } else {
            echo "<li> EXISTS </li>";
        }
    }
    echo "</ul>";
} else {
    echo "Failed to fetch email accounts!";
}
?>