<?php

date_default_timezone_set('Asia/Dhaka');
$date_time = date('Y-m-d g:i:sA');
//$date        = date('Y-m-d');
$ip_add = $_SERVER['REMOTE_ADDR'];
$userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : NULL;

$value = $obj->details_by_cond(
    "re_tbl_sms",
    "status = 1 AND reseller_id = '$userid'"
);


if (isset($_POST['clearsms'])) {
    $obj->Update_data("re_tbl_agent", ['sms_sent' => 0], "where ag_id > 0");
}

if (isset($_POST['submit'])) {

    extract($_POST);



    $form_data_sms = array(
        'smsbody' =>  $smsbody ?? NULL,
        'smshead' => isset($activeStatus) && $activeStatus == 'active' ? 'active' : 'inactive',
        'reseller_id' => $userid
    );



    if (isset($value['status']) && $value['status'] == 1) {
        $smsRow = $obj->Update_data("re_tbl_sms", $form_data_sms, " status='1' AND  reseller_id = '$userid' ");
    } else {

        $form_data_sms['status'] = 1;
        $form_data_sms['reseller_id'] = $userid;

        $smsRow = $obj->insertData("re_tbl_sms", $form_data_sms);
    }

    if ($smsRow) {
        echo '<script> window.location="?page=re_due_sms"; </script>';
    } else {

        echo $notification = 'Insert Failed';
    }
}

$allZones  =  $obj->getAllData("re_tbl_zone", ['where' => [['reseller_id', '=', $userid]]]);



// echo $obj->sendsms('$smsbody', '01687758595');
?>

<!--===================end Function===================-->

<div class="d-flex justify-content-center flex-wrap gap-4">
    <!-- Add Due SMS Section -->
    <div class="col-md-6">
        <div class="card">
            <div class="card-body">
                <!-- Form Wizard Start -->
                <div class="form-wizard">
                    <fieldset class="wizard-fieldset show">
                        <div class="text-center">
                            <div class="col-md-12 bg-teal-800">
                                <h6 class="text-md text-neutral-500">Add Due SMS</h6>
                            </div>
                            <hr>
                            <b><?php echo isset($notification) ? $notification : NULL; ?></b>
                        </div>

                        <form id="zoneSmsBodyForm" style="padding: 20px;" role="form" enctype="multipart/form-data" method="post" class="d-flex flex-column align-items-center w-100">
                            <!-- <div class="form-group w-100">
                                <label style="font-size:14px">DUE SMS Header</label>
                                <textarea class="form-control" onkeyup="countCharH(this)" name="sms_head" id="ResponsiveDetelis"
                                    rows="2" style="width: 100%;"><?php echo isset($value['smshead']) ? $value['smshead'] : NULL; ?></textarea>
                                <div><span id="charNumH"></span></div>
                            </div> -->

                            <div class="mb-3">
                                <strong style="font-size: 16px" class="badge bg-primary">{CUSTOMER_NAME}</strong>
                                <strong style="font-size: 16px" class="badge bg-secondary">{DISCONNECT_DATE}</strong>
                                <strong style="font-size: 16px" class="badge bg-success">{CUSTOMER_ID}</strong>
                                <strong style="font-size: 16px" class="badge bg-warning">{IP_ADDRESS}</strong>
                            </div>

                            <div class="form-group w-100">
                                <label style="font-size:14px">DUE SMS Details</label>
                                <textarea class="form-control" onkeyup="countCharB(this)" name="smsbody" id="ResponsiveDetelis"
                                    rows="4" style="width: 100%;"><?php echo isset($value['smsbody']) ? $value['smsbody'] : NULL; ?></textarea>
                                <div><span id="charNumB"></span></div>
                            </div>

                            <!-- <div style="display: flex; justify-content: center; align-items: center;" class="form-check mt-2 mb-5">
                                <input
                                    class="form-check-input"
                                    type="checkbox"
                                    value="active"
                                    id="excludePartiallyPaid"
                                    name="activeStatus"
                                    <?php echo isset($value['smshead']) && $value['smshead'] == 'active' ? 'checked' : ''; ?>>
                                <label class="form-check-label" style="margin-left: 0px;" for="excludePartiallyPaid">
                                    Exclude Partially Paid Clients
                                </label>
                            </div> -->

                            <button type="submit" class="btn btn-success mt-2 text-center" name="submit">SAVE SMS</button>
                        </form>
                    </fieldset>
                </div>
            </div>
        </div>
    </div>

    <!-- Send SMS To All Due Clients Section -->
    <div class="col-md-6">
        <div class="card">
            <div class="card-body">
                <!-- Form Wizard Start -->
                <div class="form-wizard">
                    <fieldset class="wizard-fieldset show">
                        <div class="text-center">
                            <div class="col-md-12 bg-teal-800">
                                <h6 class="text-md text-neutral-500">Send SMS To All Due Clients</h6>
                            </div>
                            <hr>
                        </div>

                        <form id="sendDueSmsForm" style="padding:20px;" class="w-100">

                            <div class="form-group w-100">
                                <label>Select Zone</label>
                                <select class="form-control" name="zone" required>
                                    <option value="x">All Zones Due Clients</option>
                                    <?php foreach ($allZones as $singleZone) { ?>
                                        <option value="<?= $singleZone['zone_id']; ?>">
                                            <?= $singleZone['zone_name']; ?>
                                        </option>
                                    <?php } ?>
                                </select>
                            </div>
                            <?php $disconnectDays = $obj->rawSql("SELECT DISTINCT mikrotik_disconnect FROM re_tbl_agent WHERE entry_by = '$userid' ORDER BY mikrotik_disconnect ASC"); ?>

                            <div class="form-group w-100 mt-2">
                                <label>Disconnect Date</label>
                                <select name="mikrotik_disconnect" class="form-control">
                                    <option value="0">Select</option>
                                    <?php foreach ($disconnectDays as $disconnectDay) { ?>
                                        <option value="<?= $disconnectDay['mikrotik_disconnect']; ?>">
                                            <?= $disconnectDay['mikrotik_disconnect']; ?>
                                        </option>
                                    <?php } ?>
                                </select>
                            </div>

                            <input type="hidden" name="randcheck" value="<?= $_SESSION['rand'] = 1; ?>">
                            <input type="hidden" name="excPartialPaid" value="<?= ($value['smshead'] == 'active') ? 'active' : 'inactive'; ?>">

                            <button type="submit" class="btn btn-success mt-3">
                                SEND SMS TO DUE CLIENTS
                            </button>
                        </form>
                    </fieldset>
                </div>
            </div>
        </div>
    </div>
</div>


<?php $obj->start_script(); ?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    document.getElementById('sendDueSmsForm').addEventListener('submit', function(e) {
        e.preventDefault();

        Swal.fire({
            title: 'Are you sure?',
            text: 'SMS will be sent to due clients',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, Send SMS'
        }).then((result) => {
            if (result.isConfirmed) {

                let formData = new FormData(this);

                Swal.fire({
                    title: 'Sending SMS...',
                    allowOutsideClick: false,
                    didOpen: () => Swal.showLoading()
                });

                fetch('pages/resellers/sms/ajax_send_due_sms.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(async res => {
                        let data;
                        try {
                            data = await res.json();
                        } catch (err) {
                            Swal.fire({
                                icon: 'error',
                                title: 'Invalid Response',
                                text: 'Server returned invalid JSON. Check console.'
                            });
                            const text = await res.clone().text();
                            console.error('Invalid JSON:', text);
                            return;
                        }

                        Swal.close();
                        Swal.fire({
                            icon: data.status === 'success' ? 'success' : 'error',
                            title: data.title || 'Notice',
                            text: data.message || ''
                        }).then(() => {
                            if (data.redirect) {
                                window.location = data.redirect;
                            }
                        });
                    })
                    .catch(err => {
                        Swal.fire({
                            icon: 'success',
                            title: 'success',
                            text: 'Sms Send Successfully'
                        });
                        console.error('Fetch error:', err);
                    });
            }
        });
    });
</script>



<script type="text/javascript">
    function countCharH(val) {
        var len = val.value.length;
        if (len >= 900) {
            val.value = val.value.substring(0, 900);
        } else {
            $('#charNumH').text(900 - len);
        }
    };

    function countCharB(val) {
        var len = val.value.length;
        if (len >= 900) {
            val.value = val.value.substring(0, 900);
        } else {
            $('#charNumB').text(900 - len);
        }
    };

    function confirmSendSMS() {
        return confirm("Are you sure you want to send SMS to due clients?");
    }


    document.addEventListener("DOMContentLoaded", function() {
        document.getElementById("excludePartiallyPaid").addEventListener("change", function() {
            if (this.checked) {
                document.getElementById("excPartialPaid").value = "active";
            } else {
                document.getElementById("excPartialPaid").value = "inactive";
            }
        });
    });
</script>


<?php $obj->end_script(); ?>