<?php
include "pin/header.php";
include "pin/sidenav.php";

$user_id = $_SESSION['user_id'];
$emp_id = $_SESSION['emp_id'];
$user_role = $_SESSION['user_role'];

$edit_id = mysqli_real_escape_string($db, base64_decode($_GET['edit']));
$edit = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM `letters_of_intent` WHERE `id`='$edit_id' "));

?>
<style>
    .gap-1 {
        gap: 1rem;
    }
</style>

<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->

<div class="content-page">
    <div class="content">
        <div class="container-fluid">
            <div class="mt-5"></div>

            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body p-4">
                            <h4 class="header-title mt-1 mb-4">
                                Full Time Letter
                            </h4>

                            <form id="form_submit" class="needs-validation" novalidate>
                                <div class="row">

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="loi_subject">LOI Subject<span class="text-danger">*</span></label>
                                            <input type="text" name="loi_subject" required placeholder="Enter LOI Subject" class="form-control" id="loi_subject" value="<?php echo $edit['loi_subject']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="applicant_name">Applicant Name<span class="text-danger">*</span></label>
                                            <input type="text" name="applicant_name" placeholder="Enter Applicant Name" class="form-control" id="applicant_name" value="<?php echo $edit['applicant_name']; ?>" required>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="applicant_email">Applicant Email<span class="text-danger">*</span></label>
                                            <input type="text" name="applicant_email" placeholder="Enter applicant Email" class="form-control" id="applicant_email" value="<?php echo $edit['applicant_email']; ?>" required>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="applicant_mobile">Applicant Mobile<span class="text-danger">*</span></label>
                                            <input type="text" name="applicant_mobile" placeholder="Enter applicant Mobile" class="form-control" id="applicant_mobile" value="<?php echo $edit['applicant_mobile']; ?>" required>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="date_of_joining">Joining Date<span class="text-danger">*</span></label>
                                            <input type="date" name="date_of_joining" required class="form-control" id="date_of_joining" value="<?php echo (isset($edit['date_of_joining']) ? ((!empty($edit['date_of_joining'])) ? date("Y-m-d", strtotime($edit['date_of_joining'])) : '') : ''); ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="offer_position">Offer Position<span class="text-danger">*</span></label>
                                            <input type="text" name="offer_position" required placeholder="Enter Offer Position" class="form-control" id="offer_position" value="<?php echo $edit['offer_position']; ?>">
                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="is_on_trial">Is On Trial<span class="text-danger">*</span></label>
                                                    <select name="is_on_trial" id="is_on_trial" class="form-control custom-select-picker" data-plugin="customselect" data-placeholder="Select Is On Trial">
                                                        <option>Select Is On Trial</option>
                                                        <option value="1" <?php echo ($edit['is_on_trial'] == 1) ? 'selected' : ''; ?>>Yes</option>
                                                        <option value="0" <?php echo (!empty($edit['is_on_trial']) && $edit['is_on_trial'] == 0) ? 'selected' : ''; ?>>No</option>
                                                    </select>
                                                </div>
                                            </div>
        
                                            <div class="col-md-6" style="display:none;">
                                                <div class="form-group">
                                                    <label for="trial_period_days">Trial Period (In Days)<span class="text-danger">*</span></label>
                                                    <input type="number" name="trial_period_days" pattern="[0-9]+" placeholder="Enter Trial Period" class="form-control" id="trial_period_days" value="<?php echo $edit['trial_period_days']; ?>">
                                                </div>
                                            </div>
        
                                            <div class="col-md-6" style="display:none;">
                                                <div class="form-group">
                                                    <label for="trial_period_stipend">Trial Period (Amount)<span class="text-danger">*</span></label>
                                                    <input type="number" name="trial_period_stipend" pattern="[0-9]+" placeholder="Enter Trial Period Amount" class="form-control" id="trial_period_stipend" value="<?php echo $edit['trial_period_amount']; ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="row" id="employment_block">


                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="employment_type">Employment Type<span class="text-danger">*</span></label>
                                                    <select name="employment_type" id="employment_type" class="form-control custom-select-picker" data-plugin="customselect" data-placeholder="Select Employment Type">
                                                        <option>Select Employment Type</option>
                                                        <option value="full_time" <?php echo ($edit['employment_type'] == 'full_time') ? 'selected' : ''; ?>>Full Time</option>
                                                        <option value="part_time" <?php echo ($edit['employment_type'] == 'part_time') ? 'selected' : ''; ?>>Part Time</option>
                                                        <option value="internship" <?php echo ($edit['employment_type'] == 'internship') ? 'selected' : ''; ?>>Internship</option>
                                                    </select>
                                                </div>
                                            </div>
        
                                            <div class="col-md-6" style="display:none;">
                                                <div class="form-group">
                                                    <label for="offer_ctc">Offer CTC<span class="text-danger">*</span></label>
                                                    <input type="number" name="offer_ctc" pattern="[0-9]+" placeholder="Enter Offer CTC" class="form-control" id="offer_ctc" value="<?php echo $edit['offer_ctc']; ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6" style="display:none;">
                                                <div class="form-group">
                                                    <label for="internship_period">Internship Period (In Months)<span class="text-danger">*</span></label>
                                                    <input type="number" name="internship_period" pattern="[0-9]+" placeholder="Enter Internship Period" class="form-control" id="internship_period" value="<?php echo $edit['internship_period']; ?>">
                                                </div>
                                            </div>

                                            <div class="col-12" id="internship_stipend_block" style="display: none;"></div>

                                        </div>
                                    </div>


                                </div>

                                <?php if (isset($edit['id'])) { ?>
                                    <input type="hidden" name="update_loi" id="update_loi" value="Update LOI">
                                    <input type="hidden" name="edit_id" id="edit_id" value="<?php echo $edit['id']; ?>">
                                <?php } else { ?>
                                    <input type="hidden" name="add_loi" id="add_loi" value="Add LOI">
                                <?php } ?>

                                <div class="form-group text-right mb-0 mt-4">
                                    <?php if (isset($edit['id'])) { ?>
                                        <button class="btn btn-primary mr-1" name="update_loi" id="update_loi" type="submit">Update LOI</button>
                                    <?php } else { ?>
                                        <button class="btn btn-primary mr-1" name="add_loi" id="add_loi" type="submit">Add LOI</button>
                                    <?php } ?>
                                </div>

                            </form>
                        </div>
                    </div> <!-- end card -->
                </div>
                <!-- end col -->

            </div>
            <!-- end row -->

        </div>
    </div> <!-- content -->

</div>

<!-- ============================================================== -->
<!-- End Page content -->
<!-- ============================================================== -->

<?php
include "pin/footer.php";
?>
<script src="https://cdn.ckeditor.com/4.21.0/standard/ckeditor.js"></script>
<script>
    $('#is_on_trial').change(function(e){
        if(e.target.value == 1){
            $('#trial_period_days').prop('required', true);
            $('#trial_period_days').parent().parent().show();
            $('#trial_period_stipend').prop('required', true);
            $('#trial_period_stipend').parent().parent().show();
        } else {
            $('#trial_period_days').prop('required', false);
            $('#trial_period_days').parent().parent().hide();
            $('#trial_period_stipend').prop('required', false);
            $('#trial_period_stipend').parent().parent().hide();
        }
    });

    $('#employment_type').change(function(e){
        if(e.target.value == 'internship'){
            $('#internship_period').prop('required', true);
            $('#internship_period').parent().parent().show();

            $('#offer_ctc').prop('required', false);
            $('#offer_ctc').parent().parent().hide();
        } else {
            $('#internship_period').prop('required', false);
            $('#internship_period').parent().parent().hide();

            $('#offer_ctc').prop('required', true);
            $('#offer_ctc').parent().parent().show();
        }
    });

    $('#internship_period').on('input', function(e) {
        if (e.target.value !== '') {
            $('#internship_stipend_block').show();
            let block = '<div class="d-flex gap-1 flex-wrap">';
            for (let index = 0; index < e.target.value; index++) {
                block += `<input type="text" class="form-control" name="internship_stipend[]" placeholder="Month ${index + 1} Stipend" required style="flex: 1 0 calc(100% / 4); max-width:32%;">`;
            }
            block += '</div>';
            $('#internship_stipend_block').html(block);
        } else {
            $('#internship_stipend_block').hide();
            $('#internship_stipend_block').html('');
        }
    });


    <?php if (isset($edit['id'])) { ?>
        (function(){
            let total_payout = <?php echo $edit['total_payout'] ?? json_encode([]); ?>;
            console.log(total_payout);

            if($('#is_on_trial').val()==1){
                $('#trial_period_days').prop('required', true);
                $('#trial_period_days').parent().parent().show();
                $('#trial_period_stipend').prop('required', true);
                $('#trial_period_stipend').val(total_payout.trial_period_stipend);
                $('#trial_period_stipend').parent().parent().show();
            } else {
                $('#trial_period_days').prop('required', false);
                $('#trial_period_days').parent().parent().hide();
                $('#trial_period_stipend').prop('required', false);
                $('#trial_period_stipend').parent().parent().hide();
            }


            if($('#employment_type').val()=='internship'){
                $('#internship_period').prop('required', true);
                $('#internship_period').parent().parent().show();

                $('#offer_ctc').prop('required', false);
                $('#offer_ctc').parent().parent().hide();
            } else {
                $('#internship_period').prop('required', false);
                $('#internship_period').parent().parent().hide();

                $('#offer_ctc').prop('required', true);
                $('#offer_ctc').parent().parent().show();
            }


            if($('#internship_period').val()!==''){
                $('#internship_stipend_block').show();
                let block = '<div class="d-flex gap-1 flex-wrap">';
                for (let index = 0; index < $('#internship_period').val(); index++) {
                    let stipendValue = (total_payout && Array.isArray(total_payout.internship_stipend))
                                            ? (total_payout.internship_stipend[index] || '')
                                            : '';
                    block += `<input type="text" class="form-control" name="internship_stipend[]" placeholder="Month ${index + 1} Stipend" required style="flex: 1 0 calc(100% / 4); max-width:32%;" value="${stipendValue}">`;
                }
                block += '</div>';
                $('#internship_stipend_block').html(block);
            }

        })();
    <?php } ?>

    $('#form_submit').submit(function (e) {
        e.preventDefault(); // stop normal form submission

        let form = document.getElementById('form_submit');

        // check form validation
        if (!form.checkValidity()) {
            form.classList.add('was-validated');
            return false;
        }

        // let form_data = new FormData(form);
        let form_data = $('#form_submit').serialize();
        // console.log(form_data);
        // return false;

        $.ajax({
            url: 'fun/manage_loi',
            type: 'POST',
            data: form_data,
            dataType: 'json',
            success: function(res) {
                // console.log(res);
                if (res.status === 200) {
                    successMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                    setTimeout(() => {
                        location.href='all_loi';
                    }, 2000);
                } else {
                    failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                }
            },
            error: function(xhr, status, error) {
                console.log(`Error: ${JSON.stringify(error)}`);
            }
        });
    });
</script>