<?php
require_once './includes/sms_helper.php';       // sendSms()
require_once './includes/email_helper.php';     // sendEmail()
require_once './includes/logging_helper.php';   // logCommunication()
 require './vendor/autoload.php';

function notifyMember($pdo, $memberId, $type, $placeholders = []) {
    // Get member phone and email
    $stmt = $pdo->prepare("SELECT phone_number, email_address FROM members WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $memberId]);
    $member = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$member) {
        return [["type" => "error", "message" => "Member ID $memberId not found."]];
    }

    // Load template
    $stmt = $pdo->prepare("SELECT * FROM notification_templates WHERE type = :type LIMIT 1");
    $stmt->execute([':type' => $type]);
    $template = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$template) {
        return [["type" => "error", "message" => "Template for '$type' not found."]];
    }

    $responses = [];

    // Send SMS if enabled and member has a phone
    if ($template['send_sms'] && !empty($member['phone_number'])) {
        $phone = sanitizePhone($member['phone_number']);
        $sms = replacePlaceholders($template['template_sms'], $placeholders);
        $responses[] = sendSms($pdo, $phone, $sms);
    }

    // Send Email if enabled and member has an email
    // Send Email if enabled and member has an email
if ($template['send_email'] && !empty($member['email_address'])) {
    $email = $member['email_address'];
    $subject = $template['template_name'] ?? ucfirst(str_replace('_', ' ', $type));
    $body = replacePlaceholders($template['template_email'], $placeholders);
    $responses[] = sendEmail($email, $subject, $body);
}


    return $responses;
}

function sanitizePhone($phone) {
    $phone = preg_replace('/\D/', '', $phone);
    if (strlen($phone) == 9) return '+254' . $phone;
    if (strlen($phone) == 10 && $phone[0] == '0') return '+254' . substr($phone, 1);
    if (strlen($phone) == 12 && substr($phone, 0, 3) == '254') return '+' . $phone;
    return $phone;
}

function replacePlaceholders($template, $data) {
    foreach ($data as $key => $value) {
        $template = str_replace('{{' . $key . '}}', $value, $template);
    }
    return $template;
}



function notifyAdminsNewMember($pdo, $memberId) {
    // 1. Get new member details
    $stmt = $pdo->prepare("
        SELECT id, CONCAT(first_name, ' ', middle_name, ' ', last_name) AS full_name, 
               phone_number, email_address, created_at
        FROM members 
        WHERE id = :id 
        LIMIT 1
    ");
    $stmt->execute([':id' => $memberId]);
    $member = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$member) {
        return ["error" => "Member ID $memberId not found."];
    }

    // 2. Get all admin users (via roles table)
    $stmt = $pdo->prepare("
        SELECT u.email, u.phone 
        FROM users u
        JOIN roles r ON u.role_id = r.id
        WHERE LOWER(r.name) = 'admin'
    ");
    $stmt->execute();
    $admins = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$admins) {
        return ["error" => "No admin users with role 'admin' found."];
    }

    // 3. Prepare placeholders for notification
    $placeholders = [
        'member_name'      => $member['full_name'],
        'phone_number'     => $member['phone_number'],
        'email_address'    => $member['email_address'],
        'member_id'        => $member['id'],
        'registration_date'=> date('Y-m-d H:i:s', strtotime($member['created_at']))
    ];

    // 4. Load notification template
    $stmt = $pdo->prepare("SELECT * FROM notification_templates WHERE type = 'new_member_registration' LIMIT 1");
    $stmt->execute();
    $template = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$template) {
        return ["error" => "Notification template for 'new_member_registration' not found."];
    }

    // 5. Prepare notification content
    $smsMessage   = replacePlaceholders($template['template_sms'], $placeholders);
    $emailBody    = replacePlaceholders($template['template_email'], $placeholders);
    $emailSubject = $template['template_name'] ?? 'New Member Registered';

    $responses = [];

    // 6. Notify each admin
    foreach ($admins as $admin) {
        if ($template['send_sms'] && !empty($admin['phone'])) {
            require_once './includes/sms_helper.php';
            $responses[] = sendSms($pdo, sanitizePhone($admin['phone']), $smsMessage);
        }
        if ($template['send_email'] && !empty($admin['email'])) {
            require_once './includes/email_helper.php';
            $responses[] = sendEmail($admin['email'], $emailSubject, $emailBody);
        }
    }

    return $responses;
}


?>





