<?php session_start();
$pageSequence = $_SESSION['sequence'];
$toDiv = "contentZone" . $pageSequence;
$resultZoneDiv = "resultZone" . $pageSequence;
$tableZone ="#tableZone".$pageSequence;
$_SESSION['sequence']++;


$currentBaseDir = dirname($_SERVER['PHP_SELF']);
include($_SESSION['basedir']."core.php");
$res = $dba->getSCCSmsDetails(0);

?>

<div id="<?php echo $toDiv; ?>" class="tab-content">
    <!-- Header -->
    <section class="content-header">
        <div class="header-icon">
            <i class="fa fa-envelope"></i>
        </div>
        <div class="header-title">
            <h1>Campagnes SMS</h1>
            <small>Gestion des campagnes SMS en cours</small>
        </div>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-sm-12">
                <div class="panel panel-bd lobidrag">
                    <div class="panel-heading">
                        <div class="btn-group">
                            <a href="#">
                                <h4>Liste des campagnes SMS</h4>
                            </a>
                        </div>
                    </div>

                    <div class="panel-body">
                        <!-- Boutons -->
                        <div class="btn-group">
                            <button id="addBtnCallReason" class="btn btn-sm" data-href="<?php echo $currentBaseDir; ?>/create_sms_campaign.php?toDiv=<?php echo $toDiv; ?>&rpage=<?php echo $_SERVER['PHP_SELF']; ?>" title="Créer une campagne.">
                                <i class="cus-add"></i> Créer
                            </button>
                            <button class="btn btn-sm" id="callreason-delete" disabled="disabled">
                                <i class="cus-delete"></i> Supprimer
                            </button>
                        </div>

                        <!-- Tableau -->
                        <div style="overflow: auto">
                            <table id="tblMailMngt" class="table table-striped table-bordered" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th width="3%"></th>
                                        <th width="1%"></th>
                                        <th>Date de création</th>
                                        <th>Nom de la campagne</th>
                                        <th>Statut</th>
                                        <th>&nbsp;</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($res as $row) : ?>
                                        <tr>
                                            <td><input type="checkbox" name="callReason" value="<?= $row['campaign_id_n'] ?>" class="delete-callreason" /></td>
                                            <td><a href="#" data-href="<?= $currentBaseDir; ?>/edit_sms_campaign.php?item=<?= $row['campaign_id_n']; ?>&toDiv=<?= $toDiv; ?>&rpage=<?= $_SERVER['PHP_SELF']; ?>" class="cus-application-form-edit" title="Modifier"></a></td>
                                            <td><?= $row['creation_date_d']; ?></td>
                                            <td><?= $row['campaign_name_v']; ?></td>
                                            <td><?= $row['description_v']; ?></td>
                                            <td>
                                                <?php
                                                    $status = intval($row['status_n']);
                                                    $campaignId = $row['campaign_id_n'];
                                                    $icon = '';
                                                    $tooltip = '';
                                                    $class = '';

                                                    switch ($status) {
                                                        case -1:
                                                            $icon = 'fa-play';
                                                            $tooltip = 'Initialisée - Démarrer la campagne';
                                                            $class = 'btn-default'; // gris neutre
                                                            break;
                                                        case 6:
                                                            $icon = 'fa-pause';
                                                            $tooltip = 'Campagne en cours - Mettre en pause';
                                                            $class = 'btn-success'; // vert pour "en cours"
                                                            break;
                                                        case 4:
                                                            $icon = 'fa-play';
                                                            $tooltip = 'Campagne en pause - Reprendre';
                                                            $class = 'btn-warning'; // orange
                                                            break;
                                                        case 3:
                                                            $icon = 'fa-check';
                                                            $tooltip = 'Campagne terminée';
                                                            $class = 'btn-secondary'; // gris foncé
                                                            break;
                                                        default:
                                                            $icon = 'fa-question';
                                                            $tooltip = 'Statut inconnu';
                                                            $class = 'btn-default';
                                                            break;
                                                    }

                                                ?>
                                                <button class="btn btn-xs <?php echo $class; ?> toggle-campaign" 
                                                    data-id="<?= $campaignId; ?>" 
                                                    data-status="<?= $status; ?>" 
                                                    title="<?= $tooltip; ?>">
                                                <i class="fa <?= $icon ?>"></i>
                                                </button>
                                        </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div> <!-- /.panel-body -->
                </div> <!-- /.panel -->
            </div> <!-- /.col -->
        </div> <!-- /.row -->
    </section> <!-- /.content -->
</div>

<script src="plugins/datatables/jquery.dataTables.min.js"></script>
<script src="plugins/datatables/dataTables.bootstrap.min.js"></script>

  <script type="text/javascript" >   
    
$('#tblMailMngt').DataTable( {
  "language": {
    "search": "Filtrer:",
	"emptyTable" : "Table vide",
	"zeroRecords":    "Table vide",
	"lengthMenu":     "Nombre de lignes  _MENU_ ",

	"info":           "Affichage de  _START_ &aacute; _END_ sur  _TOTAL_ entr&eacute;es",
	"paginate": {
        "first":      "D&eacute;but",
        "last":       "Fin",
        "next":       "Suivant",
        "previous":   "Pr&eacute;c&eacute;dent"
    },
	"infoEmpty":      "Affichage de  0 &agrave; 0 sur  0 entr&eacute;es"
  }
});
</script>

<script>
$('#addbtn2345').on('click',function(){
	 var dataURL = $(this).attr('data-href');
	 var modalTitle = $(this).attr('title'); 
	 $('.modal-title').html(modalTitle) ;
    $('.modal-body').load(dataURL ,function(){
        $('#myModalDesc').modal({
		 backdrop:'static',
		 keyboard: false
		});
    });
});
</script>

<script id="ajax" type="text/javascript">
var $modal = $('#myModal');

$('#addBtnCallReason').on('click', function(){
    $('#loader').loading({
        message: "Chargement...",
        theme: 'dark'
    });

    var dataURL = $(this).attr('data-href');
    var toDivId = $(this).attr('data-href').split("toDiv=")[1].split("&")[0];

    $("#" + toDivId).load(dataURL, function () {
        $('#loader').loading('stop');
    });
});
$("a.cus-application-form-edit").on('click', function(e) {
    e.preventDefault();

    $('#loader').loading({
        message: "Chargement...",
        theme: 'dark'
    });

    var dataURL = $(this).attr('data-href');
    var toDivId = dataURL.split("toDiv=")[1].split("&")[0];

    $("#" + toDivId).load(dataURL, function () {
        $('#loader').loading('stop');
    });
});

var checkBoxes = $('tbody .delete-callreason');
checkBoxes.change(function () {
    $('#callreason-delete').prop('disabled', checkBoxes.filter(':checked').length < 1);	
});
checkBoxes.change(); // or add disabled="true" in the HTML
$("#callreason-delete").on("click",function(){
	var deleteData= "";
    checkBoxes.each(function() {
        if ($(this).is(":checked")) {
			deleteData = deleteData+ "'" +  $(this).get(0).value +  "'," ;
            
        }
    });	
	deleteData = deleteData.substring(0, deleteData.length - 1);	
	$.confirm({
    title: 'Attention!',
    content: 'Voulez-vous supprimer les éléments selectionnés?',
    buttons: {
        confirm: {
		  text : 'Confirmer',
		  btnClass: 'btn-blue',
		  action: function () {			  
			  $.getJSON('<?php echo $currentBaseDir ?>/exec_delete_callreason.php?data=' + deleteData,
						function(obj) {		   
							   if(obj.errorCode == 0 ) {								 
								 $.alert({
									 icon: 'glyphicon glyphicon-ok',
									 title: 'RESULTAT',
									 content: obj.errorMessage,
									 type: 'green',
									 typeAnimated: true
					
									});
								$("#<?php echo $toDiv; ?>").load('<?php echo $_SERVER['PHP_SELF']; ?>');
								$('#loader').hide();			   
		   }
		   else {
			   
			   $.alert({
				     icon: 'glyphicon glyphicon-warning-sign',
					 title: 'RESULTAT',
                     content: obj.errorMessage,
                     type: 'red',
                     typeAnimated: true
				});
		   }
				});            
        } },
        cancel: {
		  text: 'Annuler', 
		  action:  function () {        
        }
	  }
    }
});
	
});

$(".toggle-campaign").on("click", function () {
    let campaignId = $(this).data("id");
    let currentStatus = parseInt($(this).data("status"));

    let newStatus;
    let actionLabel;

    if (currentStatus === -1) {
        newStatus = 6; // Démarrer
        actionLabel = "démarrer";
    } else if (currentStatus === 6) {
        newStatus = 4; // Pause
        actionLabel = "mettre en pause";
    } else if (currentStatus === 4) {
        newStatus = 6; // Reprendre
        actionLabel = "reprendre";
    } else {
        $.alert({
            title: "Information",
            content: "Cette campagne est déjà terminée ou ne peut pas être modifiée.",
            type: "blue"
        });
        return;
    }

    $.confirm({
        title: "Confirmation",
        content: "Voulez-vous vraiment " + actionLabel + " cette campagne ?",
        buttons: {
            confirm: {
                text: "Confirmer",
                btnClass: "btn-green",
                action: function () {
                    $.post("<?php echo $currentBaseDir; ?>/toggle_sms_campaign_status.php", {
                        campaignId: campaignId,
                        status: newStatus
                    }, function (response) {
                        try {
                            // Par précaution, parser uniquement si string
                            let obj = (typeof response === 'string') ? JSON.parse(response) : response;

                            if (obj.errorCode === 0) {
                                $.alert({
                                    icon: 'glyphicon glyphicon-ok',
                                    title: "Succès",
                                    content: obj.errorMessage,
                                    type: "green"
                                });
                                // Reload le bloc
                                $("#<?php echo $toDiv; ?>").load('<?php echo $_SERVER["PHP_SELF"]; ?>');
                            } else {
                                $.alert({
                                    icon: 'glyphicon glyphicon-warning-sign',
                                    title: "Erreur",
                                    content: obj.errorMessage,
                                    type: "red"
                                });
                            }
                        } catch (e) {
                            console.error("Erreur de parsing JSON", response);
                            $.alert({
                                title: "Erreur serveur",
                                content: "Impossible de traiter la réponse serveur.",
                                type: "red"
                            });
                        }
                    });
                }
            },
            cancel: {
                text: "Annuler",
                action: function () {
                    // Rien à faire
                }
            }
        }
    });
});


</script> 
<script type="text/javascript" src="js/jquery.loading.min.js"></script>
<link rel="stylesheet" href="css/jquery-confirm.min.css">
<script src="js/jquery-confirm.min.js"></script>