<?php $this->load->view('admin/header_list'); ?>
<div class="wrapper">
<?php $this->load->view('admin/top'); ?>
<?php $this->load->view('admin/side'); ?>
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        <?php echo $page_title; ?>
      </h1>
    </section>

    <!-- Main content -->
    <section class="content">

      <!-- Default box -->
      <div class="box">
        <div class="box-header with-border">
          <h3 class="box-title">Gallery Filters</h3>

          <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
              <i class="fa fa-minus"></i></button>
            <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
              <i class="fa fa-times"></i></button>
          </div>
        </div>
		<div class="box-header with-border">
            <div class="row">
                <div class="col-md-3">
                    <label>Client</label>
                    <select id="client_code" class="form-control">
                        <option value="">Select Client</option>
                        <?php foreach($clients as $client): ?>
                            <option value="<?php echo $client->client_code; ?>"><?php echo $client->name; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label>Photo Category</label>
                    <select id="photo_category_id" class="form-control">
                        <option value="">Select Category</option>
                        <?php foreach($photo_categories as $cat): ?>
                            <option value="<?php echo $cat->photo_category_id; ?>"><?php echo $cat->photo_category_name; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                 <div class="col-md-3">
                    <label>Function Category</label>
                    <select id="function_category_id" class="form-control">
                        <option value="">Select Function</option>
                        <?php foreach($function_categories as $func): ?>
                            <option value="<?php echo $func->function_category_id; ?>"><?php echo $func->function_category_name; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label>&nbsp;</label><br>
                    <button class="btn btn-primary" onclick="loadPhotos()">Filter</button>
                    <button class="btn btn-success" onclick="previewSelected()">Preview Selected</button>
                    <div style="margin-top: 5px;">
                        <button class="btn btn-info" onclick="openEmailModal()">Send Email</button>
                        <button class="btn btn-success" style="background-color: #25D366; border-color: #25D366;" onclick="openWhatsappModal()">WhatsApp</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="box-body">
			<div id="gallery_grid" class="row">
                <!-- Photos will be loaded here -->
            </div>
            <div id="pagination" class="text-center">
                <!-- Pagination links will be loaded here -->
            </div>
		</div>
        <!-- /.box-body -->
        <div class="box-footer">
        </div>
      </div>
      <!-- /.box -->

    </section>
    <!-- /.content -->
  </div>
  
  <!-- Modal for Preview -->
<div id="imageModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-lg">
    <div class="modal-content" style="background: transparent; box-shadow: none; border: none;">
      <div class="modal-header" style="border: none;">
        <button type="button" class="close" data-dismiss="modal" style="color: #fff; opacity: 1; text-shadow: none; font-size: 30px;">&times;</button>
        <h4 class="modal-title" style="color: #fff;">Photo Preview</h4>
      </div>
      <div class="modal-body text-center" style="position: relative;">
        <a href="javascript:void(0)" onclick="prevImage()" style="position: absolute; left: 0; top: 50%; color: #fff; font-size: 40px; text-decoration: none; transform: translateY(-50%); text-shadow: 2px 2px 4px #000;">&laquo;</a>
        <img id="previewImage" src="" style="max-width: 100%; max-height: 80vh; border: 5px solid #fff; border-radius: 4px;">
        <a href="javascript:void(0)" onclick="nextImage()" style="position: absolute; right: 0; top: 50%; color: #fff; font-size: 40px; text-decoration: none; transform: translateY(-50%); text-shadow: 2px 2px 4px #000;">&raquo;</a>
        <p id="previewTitle" style="color: #fff; margin-top: 10px; font-size: 16px; background: rgba(0,0,0,0.5); display: inline-block; padding: 5px 10px; border-radius: 4px;"></p>
      </div>
    </div>

  </div>
</div>

<!-- Modal for Email -->
<div id="emailModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Send Photos via Email</h4>
      </div>
      <div class="modal-body">
        <div class="form-group">
            <label>Recipient Email:</label>
            <input type="email" id="recipient_email" class="form-control" placeholder="Enter Client Email">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" onclick="sendEmail()">Send</button>
      </div>
    </div>
  </div>
</div>

<!-- Modal for WhatsApp -->
<div id="whatsappModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Send Photos via WhatsApp</h4>
      </div>
      <div class="modal-body">
        <div class="form-group">
            <label>Recipient Mobile No:</label>
            <input type="text" id="recipient_mobile" class="form-control" placeholder="Enter Mobile Number">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-success" style="background-color: #25D366; border-color: #25D366;" onclick="sendWhatsapp()">Send</button>
      </div>
    </div>
  </div>
</div>

  <script type="text/javascript">
	var currentPage = 0;
    var selectedImages = [];
    var currentImageIndex = 0;

	function loadPhotos(page) {
        if (typeof page === 'undefined') {
            page = 0;
        }
        currentPage = page;

        var client_code = $('#client_code').val();
        var photo_category_id = $('#photo_category_id').val();
        var function_category_id = $('#function_category_id').val();

		var current_user = "<?php echo $this->session->userdata('uname'); ?>";
        $.ajax({
            url: '<?php echo base_url(); ?>studio/get_gallery_photos',
            type: 'POST',
            data: {
                client_code: client_code,
                photo_category_id: photo_category_id,
                function_category_id: function_category_id,
                page: page
            },
            dataType: 'json',
            success: function(data) {
                var html = '';
                if(data.photos && data.photos.length > 0) {
                    $.each(data.photos, function(index, photo) {
                        html += '<div class="col-md-3 col-sm-4 col-xs-6" style="margin-bottom: 20px;">';
                        html += '<div class="thumbnail" style="position: relative; cursor: pointer;">';
                         // Checkbox for selection
                        html += '<div style="position: absolute; top: 10px; left: 10px; z-index: 10;">';
                        html += '<input type="checkbox" class="photo-select" value="' + photo.url + '" data-title="' + photo.album_name + '" style="width: 20px; height: 20px; cursor: pointer;">';
                        html += '</div>';
                        
                        html += '<img src="<?php echo base_url(); ?>uploads/photo/' + photo.url + '" style="height: 200px; width: 100%; object-fit: cover;" onclick="singlePreview(\'' + photo.url + '\', \'' + photo.album_name.replace(/'/g, "\\'") + '\')">';
                        html += '<div style="padding: 10px;">';
                        html += '<p class="text-center" style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="' + photo.album_name + '">' + photo.album_name + '</p>';

						if(current_user == 'admin'){
							html += '<button class="btn btn-danger btn-xs btn-block" onclick="deletePhoto(' + photo.photo_details_id + ')"><i class="fa fa-trash"></i> Delete</button>';
						}

                        html += '</div>';
                        html += '</div>';
                        html += '</div>';
                    });
                } else {
                    html = '<div class="col-md-12"><p class="text-center">No photos found.</p></div>';
                }
                $('#gallery_grid').html(html);

                // Pagination
                var total_rows = parseInt(data.total_rows);
                var limit = parseInt(data.limit);
                var total_pages = Math.ceil(total_rows / limit);
                var pagination_html = '<ul class="pagination">';
                
                // Previous
                if(page > 0) {
                     pagination_html += '<li><a href="#" onclick="loadPhotos(' + (page - limit) + '); return false;">&laquo;</a></li>';
                } else {
                     pagination_html += '<li class="disabled"><a href="#">&laquo;</a></li>';
                }

                // Page Numbers
                for(var i=0; i < total_pages; i++) {
                    var offset = i * limit;
                    var active = (offset == page) ? 'active' : '';
                    pagination_html += '<li class="' + active + '"><a href="#" onclick="loadPhotos(' + offset + '); return false;">' + (i + 1) + '</a></li>';
                }

                // Next
                if((page + limit) < total_rows) {
                    pagination_html += '<li><a href="#" onclick="loadPhotos(' + (page + limit) + '); return false;">&raquo;</a></li>';
                } else {
                     pagination_html += '<li class="disabled"><a href="#">&raquo;</a></li>';
                }

                pagination_html += '</ul>';
                
                if(total_rows > 0) {
                    $('#pagination').html(pagination_html);
                } else {
                    $('#pagination').html('');
                }
            }
        });
    }
    
    function singlePreview(url, title) {
        selectedImages = [{url: url, title: title}]; // Just one image
        currentImageIndex = 0;
        // Hide navigation arrows for single image
        $('a[onclick="prevImage()"]').hide();
        $('a[onclick="nextImage()"]').hide();
        showImage();
        $('#imageModal').modal('show');
    }

    function getSelectedPhotos() {
        var photos = [];
        $('.photo-select:checked').each(function() {
            photos.push($(this).val());
        });
        return photos;
    }

    function openEmailModal() {
        if(getSelectedPhotos().length == 0) {
            alert('Please select at least one photo.');
            return;
        }
        $('#emailModal').modal('show');
    }

    function openWhatsappModal() {
         if(getSelectedPhotos().length == 0) {
            alert('Please select at least one photo.');
            return;
        }
        $('#whatsappModal').modal('show');
    }

    function sendEmail() {
        var email = $('#recipient_email').val();
        if(!email) { alert('Please enter an email.'); return; }
        
        var photos = getSelectedPhotos();
        
        $.ajax({
            url: '<?php echo base_url(); ?>studio/send_gallery_email',
            type: 'POST',
            data: { email: email, photos: photos },
            success: function(response) {
                if(response == 'success') {
                    alert('Email sent successfully!');
                    $('#emailModal').modal('hide');
                } else {
                    alert('Failed to send email.');
                }
            }
        });
    }

    function sendWhatsapp() {
        var mobile = $('#recipient_mobile').val();
         if(!mobile) { alert('Please enter a mobile number.'); return; }
         var photos = getSelectedPhotos();
         
         $.ajax({
            url: '<?php echo base_url(); ?>studio/send_gallery_whatsapp',
            type: 'POST',
            data: { mobile: mobile, photos: photos },
            success: function(response) {
                if(response == 'success') {
                    alert('WhatsApp message sent successfully!');
                    $('#whatsappModal').modal('hide');
                    
                    // Client-side construction of wa.me link as a fallback/immediate action
                    var text = "Check out these photos: ";
                    // Limit text length for URL safety
                     for(var i=0; i<Math.min(photos.length, 5); i++) {
                         text += ' ' + '<?php echo base_url(); ?>uploads/photo/' + photos[i];
                     }
                      if(photos.length > 5) text += " ... and " + (photos.length - 5) + " more.";
                     
                    window.open('https://wa.me/' + mobile + '?text=' + encodeURIComponent(text), '_blank');
                    
                } else {
                    alert('Failed to send WhatsApp message.');
                }
            }
        });
    }

    function previewSelected() {
        selectedImages = [];
        $('.photo-select:checked').each(function() {
            selectedImages.push({
                url: $(this).val(),
                title: $(this).data('title')
            });
        });

        if (selectedImages.length > 0) {
            currentImageIndex = 0;
            // Show navigation arrows if more than one image
            if(selectedImages.length > 1) {
                $('a[onclick="prevImage()"]').show();
                $('a[onclick="nextImage()"]').show();
            } else {
                $('a[onclick="prevImage()"]').hide();
                $('a[onclick="nextImage()"]').hide();
            }
            showImage();
            $('#imageModal').modal('show');
        } else {
            alert('Please select at least one photo to preview.');
        }
    }

    function showImage() {
        if(selectedImages.length > 0) {
            var img = selectedImages[currentImageIndex];
            $('#previewImage').attr('src', '<?php echo base_url(); ?>uploads/photo/' + img.url);
            $('#previewTitle').text(img.title);
        }
    }

    function nextImage() {
        if(selectedImages.length > 0) {
            currentImageIndex++;
            if (currentImageIndex >= selectedImages.length) {
                currentImageIndex = 0; // Loop back
            }
            showImage();
        }
    }

    function prevImage() {
        if(selectedImages.length > 0) {
            currentImageIndex--;
            if (currentImageIndex < 0) {
                currentImageIndex = selectedImages.length - 1; // Loop to end
            }
            showImage();
        }
    }
    
    function deletePhoto(id) {
        if(confirm('Are you sure you want to delete this photo?')) {
            $.ajax({
                url: '<?php echo base_url(); ?>studio/delete_gallery_photo',
                type: 'POST',
                data: { photo_details_id: id },
                success: function(response) {
                    if(response == 'success') {
                        loadPhotos(currentPage); // Reload grid at current page
                    } else {
                        alert('Failed to delete photo.');
                    }
                }
            });
        }
    }
    
    $(document).ready(function(){
        loadPhotos(0);
        
        // Keyboard navigation for slideshow
        $(document).keydown(function(e) {
            if ($('#imageModal').is(':visible')) {
                if (e.which == 37) { // Left arrow
                   prevImage();
                } else if (e.which == 39) { // Right arrow
                   nextImage();
                }
            }
        });
    });
  </script>
 <?php $this->load->view('admin/footer_list'); ?>