<?php
session_start();

if(!isset($_SESSION['user_id']))
{
    header("Location: /beauty_pos/login.php");
    exit;
}

include_once "../config/database.php";

if(isset($_POST['send_campaign']))
{
    $audience=mysqli_real_escape_string($conn,$_POST['audience']);
    $channel=mysqli_real_escape_string($conn,$_POST['channel']);
    $message=mysqli_real_escape_string($conn,trim($_POST['message']));

    if($message=="")
    {
        $_SESSION['error']="Campaign message cannot be empty.";
        header("Location: index.php");
        exit;
    }

    mysqli_query($conn,"
    INSERT INTO campaigns
    (
        audience,
        channel,
        message,
        status
    )
    VALUES
    (
        '$audience',
        '$channel',
        '$message',
        'Sent'
    )
    ");

    if($audience=="All Customers")
    {
        $customers=mysqli_query($conn,"
        SELECT
        customer_name,
        phone,
        email
        FROM customers
        ORDER BY customer_name ASC
        ");
    }
    elseif($audience=="Premium Customers")
    {
        $customers=mysqli_query($conn,"
        SELECT
        customer_name,
        phone,
        email
        FROM customers
        WHERE loyalty_points>=100
        ORDER BY loyalty_points DESC
        ");
    }
    else
    {
        $customers=mysqli_query($conn,"
        SELECT
        customer_name,
        phone,
        email
        FROM customers
        ORDER BY created_at DESC
        LIMIT 50
        ");
    }

    while($customer=mysqli_fetch_assoc($customers))
    {

        /*
        =======================================================
        SMS API
        WhatsApp API
        Email SMTP

        Future Integration Point

        Customer :
        ".$customer['customer_name']."

        =======================================================
        */

    }

    $_SESSION['success']="Campaign sent successfully.";

    header("Location: index.php");
    exit;
}

header("Location: index.php");
exit;

?>