<?php
if (!defined('PipraPay_INIT')) {
    http_response_code(403);
    exit('Direct access not allowed');
}

    if (!canAccessPage(json_decode($global_response_permission['response'][0]['permission'], true), 'payment_link', $global_user_response['response'][0]['role'])) {
        http_response_code(403);
        exit('Access denied. You need permission to perform this action. Please contact the admin.');
    }

    if (!hasPermission(json_decode($global_response_permission['response'][0]['permission'], true), 'payment_link', 'create', $global_user_response['response'][0]['role'])) {
        http_response_code(403);
        exit('Access denied. You need permission to perform this action. Please contact the admin.');
    }
?>

<style>
    .customer-list .d-flex {
        align-items: stretch; /* KEY FIX */
    }

    .customer-list .choices {
        width: 100%;
        margin-bottom: 0;
    }

    .customer-list .choices__inner {
        min-height: 40px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
    }

    .customer-list .btnCreateItem {
        display: flex;
        justify-content: center;
        align-self: stretch;
        padding: 0 12px;
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
        white-space: nowrap;
    }
</style>

<div class="page-header d-print-none" aria-label="Page header">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col">
            <!-- Page pre-title -->
                <div class="page-pretitle">
                    <ol class="breadcrumb breadcrumb-arrow mb-0">
                        <li class="breadcrumb-item"><a href="javascript:void(0)" onclick="load_content('Payment Link','<?php echo $site_url.$path_admin ?>/payment-link','nav-item-payment-link')">Payment Link</a></li>
                        <li class="breadcrumb-item active"><a href="javascript:void(0)">Create Payment Link</a></li>
                    </ol>
                </div>
                <h2 class="page-title">Create Payment Link</h2>
            </div>
        </div>
    </div>
</div>

<div class="page-body">
    <div class="container-xl">
        <div class="row g-gs">
            <div class="col-12 col-xxl-12">
                <form class="form-paymentLink-create">
                    <input type="hidden" name="action" value="paymentLink-create">
                    <input type="hidden" name="csrf_token" value="<?= $csrf_token; ?>">

                    <div class="row g-3">
                        <div class="col-lg-12">
                            <div class="card p-2">
                                <div class="card-body">
                                    <div class="row g-3">
                                        <div class="col-lg-8">
                                            <label for="username" class="form-label">Product Title <span class="text-danger">*</span></label>
                                            <div class="input-group">
                                                <input type="text" class="form-control" name="title" placeholder="Product Title" required="">
                                            </div>
                                        </div>

                                        <div class="col-lg-4">
                                            <label for="username" class="form-label">Quantity <span class="text-danger">*</span></label>
                                            <div class="input-group">
                                                <input type="text" class="form-control" name="quantity" placeholder="0" required="">
                                            </div>
                                        </div>

                                        <div class="col-lg-12">
                                            <label for="username" class="form-label">Product Description <span class="text-danger">*</span></label>
                                            <div class="input-group">
                                                <textarea name="description" class="form-control"></textarea>
                                            </div>
                                        </div>

                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label class="form-label">Currency <span class="text-danger">*</span></label>
                                                <div class="form-control-wrap">
                                                    <select class="js-select in-currency" name="currency" data-search="true" data-remove="true" data-placeholder="Select currency" required onchange="FNcurrency()">
                                                        <?php
                                                            $response_brand = json_decode(getData($db_prefix . 'currency', 'WHERE brand_id ="'.$global_response_brand['response'][0]['brand_id'].'" ORDER BY 1 DESC'), true);
                                                            if ($response_brand['status'] == true) {
                                                                foreach ($response_brand['response'] as $row) {
                                                        ?>
                                                                    <option value="<?php echo $row['code'] ?>" <?php echo ($global_brand_currency_code == $row['code']) ? 'selected' : '';?>><?php echo $row['code'] ?></option>
                                                        <?php
                                                                }
                                                            }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-lg-3">
                                            <label for="username" class="form-label">Amount <span class="text-danger">*</span></label>
                                            <div class="input-group">
                                                <span class="input-group-text bg-white currency-code">BDT</span>
                                                <input type="text" class="form-control invoice-amount" name="amount" aria-label="Amount (to the nearest dollar)" value="0" required="">
                                            </div>
                                        </div>

                                        <div class="col-lg-3">
                                            <div class="form-group">
                                                <label for="username" class="form-label">Expiry Date</label>
                                                <div class="form-control-wrap">
                                                    <input type="date" class="form-control" name="expiry_date" placeholder="dd/mm/yyyy"> 
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-lg-3">
                                            <div class="form-group">
                                                <label for="email-address" class="form-label">Status <span class="text-danger">*</span></label>
                                                <div class="form-control-wrap">
                                                    <select class="js-select" name="status" data-search="true" data-remove="true" data-placeholder="Select a status" required>
                                                        <option value="active" selected>Active</option>
                                                        <option value="inactive">Inactive</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!--items--> 
                            <!--items--> 
                            <!--items--> 
                            <div class="item-list">

                            </div>
                            <!--items--> 
                            <!--items--> 
                            <!--items--> 

                            <center>
                                <a href="javascript:void(0)" class="btn bg-white text-dark mt-3 mb-3" onclick="add_new_item()">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-plus"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 5l0 14" /><path d="M5 12l14 0" /></svg>
                                    <span>Add New Field</span>
                                </a>
                            </center>
                        </div>
                    </div>
                    
                    <div class="pt-3">
                        <button class="btn btn-primary btn-paymentLink-create" type="submit">Create</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<script data-cfasync="false">
    function FNcurrency(){
        var currency_main = document.querySelector(".in-currency").value;

        document.querySelectorAll('.currency-code').forEach(el => {
            el.innerHTML = currency_main; 
        });
    }
    FNcurrency();

    function add_new_item(){
        const itemList = document.querySelector('.item-list');

        const uniqueId = 'item-card-' + Date.now() + '-' + Math.floor(Math.random() * 1000);

        const itemCard = document.createElement('div');
        itemCard.classList.add('card', 'mt-3');
        itemCard.id = uniqueId; // ✅ unique ID added
        itemCard.innerHTML = `
            <div class="card-header align-items-center justify-content-between">
                <h3 class="card-title">Input field</h3>
                <svg class="remove-item text-danger" style=" cursor: pointer; " xmlns="http://www.w3.org/2000/svg" width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-trash"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 7l16 0" /><path d="M10 11l0 6" /><path d="M14 11l0 6" /><path d="M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12" /><path d="M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3" /></svg>
            </div>
            <div class="card-body p-4 pt-3">
                <div class="row g-3">
                    <div class="col-lg-6">
                        <div class="form-group">
                            <label for="formType" class="form-label">Form Type <span class="text-danger">*</span></label>
                            <div class="form-control-wrap">
                                <select class="js-select" name="items[${uniqueId}][formType]" id="formType" data-search="true" data-remove="true" data-placeholder="Select a type" onchange="formTypeF('${uniqueId}')" required>
                                    <option value="text" selected>Text</option>
                                    <option value="textarea">Textarea</option>
                                    <option value="select">Select</option>
                                    <option value="file">File</option>
                                    <option value="checkbox">Checkbox</option>
                                    <option value="radio">Radio</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-6">
                        <div class="form-group">
                            <label class="form-label">Field Name <span class="text-danger">*</span></label>
                            <div class="form-control-wrap">
                                <input type="text" class="form-control" name="items[${uniqueId}][fieldName]" id="fieldName" placeholder="Enter field name"  required>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-6">
                        <div class="form-group">
                            <label for="required" class="form-label">Required <span class="text-danger">*</span></label>
                            <div class="form-control-wrap">
                                <select class="js-select" name="items[${uniqueId}][required]" id="required" data-search="true" data-remove="true" data-placeholder="Select a type" required>
                                    <option value="true" selected>Yes</option>
                                    <option value="false">No</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-6 formType-File d-none">
                        <div class="form-group">
                            <label for="fileExtensions" class="form-label">File Extensions <span class="text-danger">*</span></label>
                            <div class="form-control-wrap">
                                <select class="js-select" name="items[${uniqueId}][fileExtensions][]" multiple id="fileExtensions" data-search="true" data-remove="true" data-placeholder="Select extensions">
                                    <option value="jpg">JPG</option>
                                    <option value="jpeg">JPEG</option>
                                    <option value="png">PNG</option>
                                    <option value="gif">GIF</option>
                                    <option value="webp">WEBP</option>
                                    <option value="bmp">BMP</option>
                                    <option value="svg">SVG</option>
                                    <option value="ico">ICO</option>
                                    <option value="tiff">TIFF</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-6 formType-Select d-none">
                        <div class="form-group">
                            <label class="form-label">Add Options <span class="text-danger">*</span></label>
                            <div class="form-control-wrap">
                                <input type="text" class="js-tags form-control" id="items[${uniqueId}][addOptions][]" placeholder="Type and press Enter">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // Append item card to the list
        itemList.appendChild(itemCard);

        initChoices('.js-select');
        initTags();

        // Add event listener to remove icon
        const removeBtn = itemCard.querySelector('.remove-item');
        removeBtn.addEventListener('click', function() {
            itemCard.remove();
        });
    }

    function formTypeF(itemID) {
        var item = document.querySelector("#" + itemID);

        var formType = item.querySelector('#formType').value;

        if (formType === "select" || formType === "file" || formType === "checkbox" || formType === "radio") {
            if (formType === "file") {
                item.querySelector('.formType-File').classList.remove('d-none');
                item.querySelector('.formType-Select').classList.add('d-none');
            }else{
                item.querySelector('.formType-File').classList.add('d-none');
                item.querySelector('.formType-Select').classList.remove('d-none');
            }
        } else {
            item.querySelector('.formType-File').classList.add('d-none');
            item.querySelector('.formType-Select').classList.add('d-none');
        }
    }

    $('.form-paymentLink-create').submit(function (e) {
        e.preventDefault();

        var btn = document.querySelector(".btn-paymentLink-create").innerHTML;
        document.querySelector(".btn-paymentLink-create").innerHTML = '<div class="spinner-border spinner-border-sm" role="status"><span class="visually-hidden">Loading...</span></div>';

        var formData = $(this).serialize();

        $.ajax({
            type: 'POST',
            url: '<?php echo $site_url.$path_admin ?>/dashboard',
            data: formData,
            dataType: 'json',
            success: function (response) {
                closeAllBootstrapModals();

                document.querySelector(".btn-paymentLink-create").innerHTML = btn;

                document.querySelectorAll('input[name="csrf_token"]').forEach(input => {
                    input.value = response.csrf_token;
                });
                document.querySelectorAll('input[name="csrf_token_default"]').forEach(input => {
                    input.value = response.csrf_token;
                });

                if (response.status === 'true') {
                    createToast({
                        title: response.title,
                        description: response.message,
                        svg: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#5f38f9" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-circle-check"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0" /><path d="M9 12l2 2l4 -4" /></svg>`,
                        timeout: 6000,
                        top: 70
                    });

                    load_content('Payment Link','<?php echo $site_url.$path_admin ?>/payment-link','nav-item-payment-link');
                } else {
                    createToast({
                        title: response.title,
                        description: response.message,
                        svg: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#d63939" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-exclamation-circle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0" /><path d="M12 9v4" /><path d="M12 16v.01" /></svg>`,
                        timeout: 6000,
                        top: 70
                    });
                }
            },
            error: function (xhr, status, error) {
                createToast({
                    title: 'Something Wrong!',
                    description: 'For further assistance, please contact our support team.',
                    svg: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#d63939" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-exclamation-circle"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0" /><path d="M12 9v4" /><path d="M12 16v.01" /></svg>`,
                    timeout: 6000,
                    top: 70
                });
            }
        });
    });
</script>