@extends('layouts.app')
@section('title', 'Add Reminder')
@section('content')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<section class="content">
  <div class="row">       
    <div class="col-lg-12 col-12">
        <div class="box">


                                
            <div class="box-body"><!--bg-lightest-->

                
                <h4 class="box-title text-info mb-0"><i class="fa fa-plus"></i> Add Reminder for {{$id}}</h4>
                <a href="{{url('/leads')}}" type="button" style="float:right" class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm mb-5"><i class="fa fa-eye fa-sx"></i> Leads</a>

                <hr class="my-15">

                <div>
                    
            


                <div class="row">
                                                        <div class="col-md-12">

                                                            <div class="box">
                                                                <div class="box-body">

                                                                    <div class="row">


                                                                    <form method="post" action="{{url('leads/addTask')}}" id="taskForm"> 
                                                                        @csrf 
                                                                        <input type="hidden" value="{{$id}}" name="lead_id">

                                                                        <!-- Notes and Notify Reminder in One Row -->
                                                                        <div class="row">
                                                                            <!-- Notify Reminder -->
                                                                            <div class="form-group col-md-3">
                                                                                <label class="form-label">Notify reminder via</label>
                                                                                <select class="form-select" name="task_name" id="">
                                                                                    <option value="">Select</option>
                                                                                    <option value="email">Email</option>
                                                                                    <option value="phone">Phone</option>
                                                                                </select>
                                                                            </div>
                                                                            <!-- Notes -->
                                                                            <div class="form-group col-md-3">
                                                                                <label class="form-label">Notes</label>
                                                                                <textarea type="text" name="notes" class="form-control" placeholder="Write Notes"></textarea>
                                                                            </div>
                                                                            <!-- Date -->
                                                                            <div class="form-group col-md-3">
                                                                                <label class="form-label">Date</label>
                                                                                <input type="date" class="form-control" name="date">
                                                                            </div>
                                                                            <!-- Time -->
                                                                            <div class="form-group col-md-3">
                                                                                <label class="form-label">Time</label>
                                                                                <div class="d-flex gap-3">
                                                                                    <!-- Hours -->
                                                                                    <div class="input-group" style="max-width: 80px;">
                                                                                        <input 
                                                                                            type="number" 
                                                                                            id="hours" 
                                                                                            class="form-control form-control-sm text-center" 
                                                                                            min="1" 
                                                                                            max="12" 
                                                                                            value="1" 
                                                                                            style="height: 40px;" 
                                                                                            oninput="updateTime()"
                                                                                        >
                                                                                        <div class="input-group-append d-flex flex-column">
                                                                                            <button type="button" class="btn btn-outline-secondary btn-sm p-0" onclick="increment('hours')" style="height: 20px;">▲</button>
                                                                                            <button type="button" class="btn btn-outline-secondary btn-sm p-0" onclick="decrement('hours')" style="height: 20px;">▼</button>
                                                                                        </div>
                                                                                    </div>

                                                                                    <!-- Minutes -->
                                                                                    <div class="input-group" style="max-width: 80px;">
                                                                                        <input 
                                                                                            type="number" 
                                                                                            id="minutes" 
                                                                                            class="form-control form-control-sm text-center" 
                                                                                            min="0" 
                                                                                            max="59" 
                                                                                            value="0" 
                                                                                            style="height: 40px;" 
                                                                                            oninput="updateTime()"
                                                                                        >
                                                                                        <div class="input-group-append d-flex flex-column">
                                                                                            <button type="button" class="btn btn-outline-secondary btn-sm p-0" onclick="increment('minutes')" style="height: 20px;">▲</button>
                                                                                            <button type="button" class="btn btn-outline-secondary btn-sm p-0" onclick="decrement('minutes')" style="height: 20px;">▼</button>
                                                                                        </div>
                                                                                    </div>

                                                                                    <!-- AM/PM -->
                                                                                    <div class="input-group" style="max-width: 80px;">
                                                                                        <input 
                                                                                            type="text" 
                                                                                            id="ampm" 
                                                                                            class="form-control form-control-sm text-center" 
                                                                                            value="AM" 
                                                                                            readonly 
                                                                                            style="height: 40px;" 
                                                                                        >
                                                                                        <div class="input-group-append d-flex flex-column">
                                                                                            <button type="button" class="btn btn-outline-secondary btn-sm p-0" onclick="toggleAMPM()" style="height: 20px;">▲</button>
                                                                                            <button type="button" class="btn btn-outline-secondary btn-sm p-0" onclick="toggleAMPM()" style="height: 20px;">▼</button>
                                                                                        </div>
                                                                                    </div>

                                                                                    <!-- Hidden Input for Combined Time -->
                                                                                    <input type="hidden" name="time" id="time" value="">
                                                                                </div>
                                                                            </div>
                                                                        </div>

                                                        
                                                                
                                                                    </div>
                                                                </div>
                                                            </div>

                                                        </div>


            
                                                    <div class="box-footer text-end">
                                                    <a href="/leads"  class="btn btn-warning me-1">
                                                        <i class="ti-trash"></i> Cancel
                                                        </a>

                                                        <a onclick="window.location.reload();"  class="btn btn-danger me-1">
                                                        <i class="ti-reload"></i> Reset
                                                        </a>

                                                        <button  type="submit" class="btn btn-primary">
                                                        <i class="ti-save-alt"></i> Submit
                                                        </button>
                                                    </div>  
                                                    </form>
                        
                    
                </div>
    <div class="row">    
<div class="table-responsive">
                <table id="tickets1" class="table mt-0 table-hover no-wrap" data-page-size="10">
                                <thead>
                                            <tr>
                                            <th>#</th>

                                        <th>Notify via</th>
                                        <th>Notes</th>
                                        <th>Date</th>

                                        <th>Time</th>
                                        <th>Created At</th>
                            
                                        <th>Action</th>

                                                                
                                        

                                            </tr>
                                </thead>
                <tbody>
                    @foreach($tasks as $key =>$task)
                    <tr>
                        <td>{{$key+1}}</td>
                        <td>{{$task->task_name}}</td>
                        <td>{{$task->notes}}</td>
                        <td>{{ \Carbon\Carbon::parse($task->date)->format('m-d-Y') }}</td>
                        <td>
                        {{ $task->time ? \Carbon\Carbon::createFromFormat('H:i:s', $task->time)->format('h:i A') : 'N/A' }}</td>

                        <td>{{ \Carbon\Carbon::parse($task->created_at)->format('m-d-Y H:i:s') }}</td>


                        <td>
                        <a style="cursor:pointer;" href="#" class="list-icons-item me-10 openLeadDelete" data-lead-id="{{$id}}"data-id="{{$task->id}}"><i class="fa fa-trash-o fa-lg"></i></a>
                </td>
                </tr>
                @endforeach
                </tbody>
</div>
</div>
            
                    <!-- /.box -->      
                <div class="modal fade" id="delete" tabindex="-1" aria-labelledby="deleteLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="myModalLabel">Confirm Delete</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        

                        <div class="modal-body">
                        <p>You are about to delete <b><i class="title"></i></b> Reminder.</p>
                                                    <p>Do you want to proceed?</p>                       
                                                    <input type="hidden" class="form-control" name="lead_id" value="{{$id}}" id="lead_id">

                            </div>                                <input type="hidden" class="form-control" name="task_id" value="" id="task_id">

                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-danger btn-ok btn-sm deleteLead">Delete</button>
                        </div>
                        </div>
                    </div>
                </div>	
            </div>
        </div>  
    </div>
  </div>
  </section>

    


<!-- JavaScript -->
<script>
function updateTime() {
    let hours = parseInt(document.getElementById('hours').value, 10); // Get hours as integer
    const minutes = document.getElementById('minutes').value.padStart(2, '0'); // Pad minutes with leading zero
    const ampm = document.getElementById('ampm').value;

    // Convert hours to 24-hour format if PM
    if (ampm === 'PM' && hours < 12) {
        hours += 12;
    } else if (ampm === 'AM' && hours === 12) {
        hours = 0; // Midnight case
    }

    // Format hours with leading zero if needed
    const formattedHours = hours.toString().padStart(2, '0');

    // Combine the time values in 24-hour format
    const combinedTime = `${formattedHours}:${minutes}`;
    document.getElementById('time').value = combinedTime;
}


function increment(id) {
    const input = document.getElementById(id);
    const max = parseInt(input.max, 10);
    let value = parseInt(input.value, 10) || 0;
    if (value < max) input.value = value + 1;
    updateTime();
}

function decrement(id) {
    const input = document.getElementById(id);
    const min = parseInt(input.min, 10);
    let value = parseInt(input.value, 10) || 0;
    if (value > min) input.value = value - 1;
    updateTime();
}

function toggleAMPM() {
    const ampm = document.getElementById('ampm');
    ampm.value = ampm.value === 'AM' ? 'PM' : 'AM';
    updateTime();
}

$(document).ready(function () {
    $('#taskForm').on('submit', function (e) {
        e.preventDefault(); // Prevent the default form submission

        // Serialize form data
        var formData = $(this).serialize();
      // Extract form values
        // Extract form values
        var taskName = $('select[name="task_name"]').val();
        var rawDate = $('input[name="date"]').val(); // Raw date (YYYY-MM-DD)
        var rawTime = $('input[name="time"]').val(); // Raw time (HH:mm)

        // Format the date to MM-DD-YYYY
        var dateParts = rawDate.split('-');
        var formattedDate = `${dateParts[1]}-${dateParts[2]}-${dateParts[0]}`;

        // Format the time to 12-hour format with AM/PM
        var timeParts = rawTime.split(':'); // Split time into hours, minutes
        var hours = parseInt(timeParts[0], 10);
        var minutes = timeParts[1];
        var ampm = hours >= 12 ? 'PM' : 'AM'; // Set AM/PM explicitly
        hours = hours % 12 || 12; // Convert to 12-hour format
        var formattedTime = `${hours}:${minutes} ${ampm}`;
        // AJAX request
        $.ajax({
            url: $(this).attr('action'), // Form action URL
            type: 'POST', // HTTP method
            data: formData, // Serialized form data
            success: function (response) {
                // Handle success (e.g., show a success message, reset the form, etc.)
                toastr.success('Task added successfully!');
                window.location.reload();
                $('#taskForm')[0].reset(); // Optional: reset the form
            },
            error: function (xhr, status, error) {
                // Handle error (e.g., display error messages)
                toastr.error('Something went wrong. Please try again.');
                console.error(xhr.responseText);
            }
        });
    });
});

</script>
<script>
$(".openLeadDelete").click(function () {
            var delete_id = $(this).data('id');
            var lead_id = $(this).data('lead-id');
            $("#delete").modal('show');
            $("#task_id").val(delete_id);
        });
        $(document).on("click", ".deleteLead", function () {
            var lead_id = $('#lead_id').val();
            var task_id = $('#task_id').val();
            $.ajax({
                url: '/leads/reminder/delete/' + lead_id + '/' + task_id, // Correct URL concatenation with slashes
                type: 'get',
                success: function (response) {
                    console.log(response);
                    window.location.reload(1);
                }
            });
        });

    </script>
     
@endsection
