<?php
function RandomString($count) {
    /*$randstr = "";
    srand((double) microtime(TRUE) * 1000000);
    //our array add all letters and numbers if you wish
    $chars = array(
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'p',
        'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5',
        '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
        'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');

    for ($rand = 0; $rand <= $length; $rand++) {
        $random = rand(0, count($chars) - 1);
        $randstr .= $chars[$random];
    }
    return $randstr;*/
    $firstrand = rand(0, 9999);
    $firstcharsno = strlen($firstrand);
    $character_set_array = array();
    $character_set_array[] = array('count' => $count-$firstcharsno, 'characters' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz');
    //$character_set_array[] = array('count' => $count, 'characters' => '');
    $temp_array = array();
    foreach ($character_set_array as $character_set) {
        for ($i = 0; $i < $character_set['count']; $i++) {
            $temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
        }
    }
    shuffle($temp_array);
    return $firstrand.implode('', $temp_array);
}

function SendMessage($title, $recipient, $fromname, $body, $con="")
{
    $sent = false;
    $mail = new PHPMailer;
    
    try {
        $mail->SMTPDebug = 1;
        
        $mail->isSMTP();
        $mail->Host = 'certify.ng';
        $mail->SMTPAuth = true;
        $mail->Username = 'noreply@certify.ng';
        $mail->Password = 'X6NS&eU(hF5D';
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465;
        
        $mail->From = 'noreply@certify.ng';
        $mail->FromName = $fromname;
        $mail->addAddress($recipient, $recipient);
        $mail->AddReplyTo('noreply@certify.ng', 'Certify.ng');
        $mail->isHTML(true);
        
        $mail->Subject = $title;
        $mail->Body    = $body;
        $mail->AltBody =  $body;
        if($mail->send()) {
            $sent = true;
        }
        else
        {
            $sent = false;
        }
    }
    catch(phpmailerException $e){
        echo $e->errorMessage();
    }
    return $sent;
}

function ReplaceTokens($body, $recipient, \database $con)
{
    $message = $body;
    $firstname = "";
    $lastname = "";
    $othername = "";
    $sql = "select firstname,lastname,othernames from staff where email=:recipient";
    $q=$con->select_query($sql,array(':recipient'=>$recipient));
    if(isset($q) && !empty($q))
    {
        foreach($q as $r)
        {
            $firstname = $r['firstname'];
            $lastname = $r['lastname'];
            $othername = $r['othernames'];
        }
    }
    
    $message = str_replace('%firstname%', $firstname, $message);
    $message = str_replace('%lastname%', $lastname, $message);
    $message = str_replace('%othername%', $othername, $message);
    return $message;
}

/**
 * Build recipient list according to participant selection saved with scheduled_mails
 * @param string $participant_type
 * @param string|null $participant_data_json
 * @param database $con
 * @return array rows from staff table
 */
function get_recipients_for_scheduled_mail($participant_type, $participant_data_json, $con)
{
    if(!$participant_type || $participant_type === 'all'){
        return $con->select_query("SELECT * FROM staff WHERE email != ?", [""]);
    }

    $data = [];
    if($participant_data_json) {
        $data = json_decode($participant_data_json, true) ?: [];
    }

    switch($participant_type){

        case 'individual':

            // get selected individual IDs
            $ids = isset($data['individuals']) ? (array)$data['individuals'] : [];

            // no individuals selected
            if(empty($ids)) return [];

            // build placeholders for IN clause
            $placeholders = implode(',', array_fill(0, count($ids), '?'));

            // query staff by selected IDs
            $sql = "SELECT * FROM staff WHERE id IN ($placeholders) AND email != ?";
            $params = array_merge($ids, [""]);

            // return the selected staff info
            return $con->select_query($sql, $params);

        case 'department':

            // get selected department IDs
            $vals = isset($data['departments']) ? (array)$data['departments'] : [];

            // no departments selected
            if(empty($vals)) return [];

            // build placeholders for IN clause
            $placeholders = implode(',', array_fill(0, count($vals), '?'));

            // query staff by selected departments
            $sql = "SELECT * FROM staff WHERE dept IN ($placeholders) AND email != ?";
            $params = array_merge($vals, [""]);

            // return the selected staff info
            return $con->select_query($sql, $params);

        case 'position':

            // get selected position IDs
            $vals = isset($data['positions']) ? (array)$data['positions'] : [];

            // no selected position
            if(empty($vals)) return [];

            // build placeholders for IN clause
            $placeholders = implode(',', array_fill(0, count($vals), '?'));

            // query staff by selected positions
            $sql = "SELECT * FROM staff WHERE position IN ($placeholders) AND email != ?";
            $params = array_merge($vals, [""]);

            // return the selected staff info
            return $con->select_query($sql, $params);

        case 'dob':

            // get date of birth range
            $start = isset($data['dob_start']) ? DATE('m-d', strtotime($data['dob_start'])) : null;
            $end = isset($data['dob_end']) ? DATE('m-d', strtotime($data['dob_end'])) : null;

            // query staff by dob range
            if($start && $end){

                if ($start <= $end) {

                    // Normal range (e.g. 03-01 to 06-30)
                    return $con->select_query("SELECT * FROM staff WHERE DATE_FORMAT(dob, '%m-%d') BETWEEN ? AND ? AND email != ?", [$start, $end, ""]);

                } else {

                    // Year-wrap range (e.g. 12-20 to 01-10)
                    return $con->select_query("SELECT * FROM staff WHERE (DATE_FORMAT(dob, '%m-%d') >= ? OR DATE_FORMAT(dob, '%m-%d') <= ?) AND email != ?", [$start, $end, ""]);

                }
                
            } elseif($start){

                return $con->select_query("SELECT * FROM staff WHERE DATE_FORMAT(dob, '%m-%d') >= ? AND email != ?", [$start, ""]);
                
            } elseif($end){
            
                return $con->select_query("SELECT * FROM staff WHERE DATE_FORMAT(dob, '%m-%d') <= ? AND email != ?", [$end, ""]);
                
            }

            // no valid dob range provided
            return [];

        default:

            // fallback to all staff
            return $con->select_query("SELECT * FROM staff WHERE email != ?", [""]);

    }
}
?>