<?php
session_start();
$currentBaseDir = dirname($_SERVER['PHP_SELF']);
include($_SESSION['basedir'] . "core.php");

$svaTool = new svaTool();
$errorCode = 0;
$campaignName = NULL;
$fileSavedName = NULL;

$today = date("Y-m-d");

$startDate = (!empty($_POST['startDate'])) ? $_POST['startDate'] : $today;
$endDate = (!empty($_POST['endDate'])) ? $_POST['endDate'] : $today;

$startTime = str_pad($_POST['startHour'], 2, '0', STR_PAD_LEFT) . ':' .
             str_pad($_POST['startMinute'], 2, '0', STR_PAD_LEFT) . ':' .
             str_pad($_POST['startSecond'], 2, '0', STR_PAD_LEFT);

$endTime = str_pad($_POST['endHour'], 2, '0', STR_PAD_LEFT) . ':' .
           str_pad($_POST['endMinute'], 2, '0', STR_PAD_LEFT) . ':' .
           str_pad($_POST['endSecond'], 2, '0', STR_PAD_LEFT);

$startDateTime = strtotime("$startDate $startTime");
$endDateTime = strtotime("$endDate $endTime");

if ($startDate === $endDate) {
    // Cas 1 : même date, on compare les heures
    if ($endTime <= $startTime) {
        $errorCode = 8; // Heure de fin ≤ début sur même date
    }
} elseif ($endDate < $startDate) {
    // Cas 2 : date de fin avant la date de début
    $errorCode = 9;
}

//$startTime = $_POST['startTime']; 
//$endTime = $_POST['endTime']; 

$userId = $_SESSION['ownerId'];
$actionType = isset($_POST['actionType']) ? intval($_POST['actionType']) : 0;

// Nom de campagne
if (isset($_POST['campaignName']) && strlen($_POST['campaignName']) > 0)
    $campaignName = trim($_POST['campaignName']);
else
    $errorCode = 1;

if ($errorCode === 0) {
    if ($actionType === 2) {
        // AJOUT
        if (isset($_FILES['phoneListFile']) && is_uploaded_file($_FILES['phoneListFile']['tmp_name'])) {
            $filename = $_FILES['phoneListFile']['name'];
            $tmpName = $_FILES['phoneListFile']['tmp_name'];
            $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

            $valid_extensions = array("txt", "csv");

            if (in_array($extension, $valid_extensions)) {
                $campaignId = $dba->createSmsCampaign($campaignName, $startDate, $startTime, $endDate, $endTime, $userId);

                if ($campaignId > 0) {
                    $handle = fopen($tmpName, "r");
                    $totalInserted = 0;
                    while (($line = fgets($handle)) !== false) {
                        $phone = trim($line);
                        if (!empty($phone)) {
                            $entity = '';
                            $statut = 0;
                            $result = $dba->upldQueuesProcessor($campaignId, $phone, $entity, $statut);
                            if ($result === 1) {
                                $totalInserted++;
                            }
                        }
                    }
                    fclose($handle);

                    $msg = json_encode([
                        "errorCode" => 0,
                        "errorMessage" => "CAMPAGNE CRÉÉE AVEC SUCCÈS. $totalInserted numéros importés."
                    ]);
                } else {
                    $errorCode = 5;
                }
            } else {
                $errorCode = 3;
            }
        } else {
            $errorCode = 3;
        }

    } elseif ($actionType === 3) {
        // MODIFICATION
        $campaignId = isset($_POST['campaignId']) ? intval($_POST['campaignId']) : 0;

        if ($campaignId > 0) {
            $updateSuccess = $dba->updateSmsCampaign($campaignId, $campaignName, $startDate, $startTime, $endDate, $endTime);
            if ($updateSuccess) {
                $msgText = "CAMPAGNE MODIFIÉE AVEC SUCCÈS.";

                // Si un fichier est envoyé pour modification
                if (isset($_FILES['phoneListFile']) && is_uploaded_file($_FILES['phoneListFile']['tmp_name'])) {
                    $filename = $_FILES['phoneListFile']['name'];
                    $tmpName = $_FILES['phoneListFile']['tmp_name'];
                    $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

                    $valid_extensions = array("txt", "csv");

                    if (in_array($extension, $valid_extensions)) {
                        // vider les anciens numéros
                         $dba->deleteAllCampaignPhones($campaignId);

                        $handle = fopen($tmpName, "r");
                        $totalInserted = 0;
                        while (($line = fgets($handle)) !== false) {
                            $phone = trim($line);
                            if (!empty($phone)) {
                                $entity = '';
                                $statut = 0;
                                $result = $dba->upldQueuesProcessor($campaignId, $phone, $entity, $statut);
                                if ($result === 1) {
                                    $totalInserted++;
                                }
                            }
                        }
                        fclose($handle);
                        $msgText .= " $totalInserted numéros importés.";
                    } else {
                        $errorCode = 3;
                    }
                }

                if ($errorCode === 0) {
                    $msg = json_encode([
                        "errorCode" => 0,
                        "errorMessage" => $msgText
                    ]);
                }
            } else {
                $errorCode = 6; // Échec de modification
            }
        } else {
            $errorCode = 7; // ID campagne invalide
        }
    }
}

// Gestion des erreurs
if ($errorCode !== 0) {
    switch ($errorCode) {
        case 1:
            $msg = '{ "errorCode": 1, "errorMessage" :"NOM DE CAMPAGNE INVALIDE OU MANQUANT." }';
            break;
        case 3:
            $msg = '{ "errorCode": 3, "errorMessage" :"FICHIER INVALIDE. (.txt ou .csv requis)" }';
            break;
        case 5:
            $msg = '{ "errorCode": 5, "errorMessage" :"ÉCHEC DE CRÉATION DE LA CAMPAGNE." }';
            break;
        case 6:
            $msg = '{ "errorCode": 6, "errorMessage" :"ÉCHEC DE MISE À JOUR DE LA CAMPAGNE." }';
            break;
        case 7:
            $msg = '{ "errorCode": 7, "errorMessage" :"ID DE CAMPAGNE INVALIDE POUR LA MISE À JOUR." }';
            break;
        case 8:
            $msg = '{ "errorCode": 8, "errorMessage" :"Pour la même date, l\'heure de fin doit être supérieure à l\'heure de début." }';
            break;
        case 9:
            $msg = '{ "errorCode": 9, "errorMessage" :"La date de fin doit être après la date de début." }';
            break;
        default:
            $msg = '{ "errorCode": 99, "errorMessage" :"ERREUR INCONNUE." }';
            break;
    }
}

echo $msg;
?>