<?php
include('header.php');
mysqli_set_charset($conn,"utf8");
$res = mysqli_query($conn, "SELECT * FROM `birthmanual` WHERE username='$s_phone'  ORDER BY id DESC ");

// Handle delete action - WITH OWNERSHIP CHECK
if(isset($_POST['delete']) && $_POST['delete'] == "ahkwebsolutions"){
    $id = mysqli_real_escape_string($conn, base64_decode($_POST['id']));
    // Security: Only allow delete if record belongs to logged-in user
    $del = mysqli_query($conn,"DELETE FROM `birthmanual` WHERE id='$id' AND username='$s_phone'");
    if($del){
        ?>
        <script>
            $(function(){
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: 'Data Deleted Successfully!',
                    confirmButtonColor: '#28a745'
                }).then(function() {
                    window.location.href = 'birthlist';
                });
            });
        </script>
        <?php
        exit;
    }else{
        ?>
        <script>
            $(function(){
                Swal.fire({
                    icon: 'error',
                    title: 'Oops!',
                    text: 'Data Not Deleted!',
                    confirmButtonColor: '#dc3545'
                });
            });
        </script>
        <?php
    }
}
?>

<!-- Font Awesome Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    .birth-list-container {
        max-width: 100%;
        margin: 20px auto;
        background: #fff;
        padding: 25px;
        border-radius: 10px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    }

    .page-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 25px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    .page-header h3 {
        margin: 0;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .page-header h3 i {
        font-size: 28px;
    }

    /* Table Styling */
    #example2 {
        border-collapse: separate !important;
        border-spacing: 0 8px !important;
    }

    #example2 thead th {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        font-weight: 600;
        text-transform: uppercase;
        font-size: 12px;
        letter-spacing: 0.5px;
        border: none;
        padding: 15px 10px;
        white-space: nowrap;
    }

    /* Name column header */
    #example2 thead th:nth-child(2) {
        white-space: normal;
    }

    #example2 tbody tr {
        background: #fff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        transition: all 0.3s ease;
    }

    #example2 tbody tr:hover {
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
        transform: translateY(-2px);
    }

    #example2 tbody td {
        vertical-align: middle;
        padding: 15px 10px;
        border: none;
    }

    /* Name column specific styling */
    #example2 tbody td:nth-child(2) {
        max-width: 200px;
        word-wrap: break-word;
        white-space: normal;
    }

    /* Action Buttons */
    .btn-action {
        padding: 8px 12px;
        border-radius: 6px;
        border: none;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 14px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-width: 40px;
        margin: 2px;
    }

    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .btn-action i {
        font-size: 14px;
    }

    .btn-download {
        background: linear-gradient(135deg, #007bff, #0056b3);
        color: white;
    }

    .btn-download:hover {
        background: linear-gradient(135deg, #0056b3, #003d82);
    }

    .btn-view {
        background: linear-gradient(135deg, #6c757d, #495057);
        color: white;
    }

    .btn-view:hover {
        background: linear-gradient(135deg, #495057, #343a40);
    }

    .btn-edit {
        background: linear-gradient(135deg, #28a745, #218838);
        color: white;
    }

    .btn-edit:hover {
        background: linear-gradient(135deg, #218838, #1e7e34);
    }

    .btn-delete {
        background: linear-gradient(135deg, #dc3545, #c82333);
        color: white;
    }

    .btn-delete:hover {
        background: linear-gradient(135deg, #c82333, #bd2130);
    }

    /* Badge Styling */
    .user-badge {
        background: linear-gradient(135deg, #17a2b8, #138496);
        color: white;
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
        display: inline-block;
    }

    .id-badge {
        background: linear-gradient(135deg, #6c757d, #495057);
        color: white;
        padding: 5px 10px;
        border-radius: 5px;
        font-weight: 600;
        display: inline-block;
    }

    /* DataTables Custom Styling */
    .dataTables_wrapper .dataTables_filter input {
        border: 2px solid #667eea;
        border-radius: 20px;
        padding: 8px 15px;
        margin-left: 10px;
    }

    .dataTables_wrapper .dataTables_length select {
        border: 2px solid #667eea;
        border-radius: 5px;
        padding: 5px 10px;
    }

    .dataTables_wrapper .dataTables_paginate .paginate_button.current {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
        color: white !important;
        border: none !important;
        border-radius: 5px;
    }

    /* Tooltip */
    [data-tooltip] {
        position: relative;
    }

    [data-tooltip]:hover::after {
        content: attr(data-tooltip);
        position: absolute;
        bottom: 100%;
        left: 50%;
        transform: translateX(-50%);
        background: #333;
        color: #fff;
        padding: 6px 10px;
        border-radius: 5px;
        white-space: nowrap;
        font-size: 12px;
        z-index: 1000;
        margin-bottom: 5px;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .btn-action {
            padding: 6px 10px;
            font-size: 12px;
            min-width: 36px;
        }
        
        .page-header h3 {
            font-size: 18px;
        }
    }
</style>

<!-- Main Content -->
<div class="birth-list-container">
    <div class="page-header">
        <h3>
            <i class="fas fa-baby"></i>
            Birth Certificate List
        </h3>
    </div>

    <div class="card">
        <div class="card-body">
            <table id="example2" class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th style="width: 80px;" class="text-center">
                            <i class="fas fa-hashtag"></i> ID
                        </th>
                        <th style="width: 200px;">
                            <i class="fas fa-user"></i> Name
                        </th>
                        <th class="text-center" style="width:120px;">
                            <i class="fas fa-user-circle"></i> User
                        </th>
                        <th style="width: 100px;" class="text-center">
                            <i class="fas fa-trash-alt"></i> Delete
                        </th>
                        <th style="width: 200px;" class="text-center">
                            <i class="fas fa-cogs"></i> Actions
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if(mysqli_num_rows($res) > 0){
                        $sr_no = 1;
                        while($data = mysqli_fetch_array($res)){
                            $name_display = trim($data['name']);
                            if(!empty($data['name_local'])){
                                $name_display .= ' (' . $data['name_local'] . ')';
                            }
                            ?>
                            <tr>
                                <td class="text-center">
                                    <span class="id-badge"><?php echo $data['id']; ?></span>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($name_display); ?></strong>
                                </td>
                                <td class="text-center">
                                    <span class="user-badge">
                                        <i class="fas fa-user"></i>
                                        <?php echo htmlspecialchars($_SESSION['name']); ?>
                                    </span>
                                </td>
                                <td class="text-center">
                                    <form action="" method="post" class="d-inline delete-form">
                                        <input type="hidden" name="id" value="<?php echo base64_encode($data['id']); ?>">
                                        <input type="hidden" name="delete" value="ahkwebsolutions">
                                        <input type="hidden" name="_method" value="DELETE">
                                        <button type="button" 
                                                class="btn-action btn-delete" 
                                                onclick="deleteRecord(this)"
                                                data-tooltip="Delete Certificate">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </td>
                                <td class="text-center">
                                    <a target="_blank" 
                                       href="birthCertificatePdf/print?id=<?php echo base64_encode($data['id']); ?>Qgh2Z8ghfjgfdgdfggdfdgsdASERWR451olwR" 
                                       class="btn-action btn-download"
                                       data-tooltip="Download PDF">
                                        <i class="fas fa-download"></i>
                                    </a>
                                    
                                    <a target="_blank" 
                                       href="verifyCertificate?id=<?php echo base64_encode($data['id']); ?>Qgh2Z8ghfjgfdgdfggdfdgsdASERWR451olwR" 
                                       class="btn-action btn-view"
                                       data-tooltip="View Certificate">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    
                                    <a href="birthedit?id=<?php echo base64_encode($data['id']); ?>Qgh2Z8ghfjgfdgdfggdfdgsdASERWR451olwR" 
                                       class="btn-action btn-edit"
                                       data-tooltip="Edit Certificate">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php
                            $sr_no++;
                        }
                    } else {
                        ?>
                        <tr>
                            <td colspan="5" class="text-center" style="padding: 40px;">
                                <i class="fas fa-inbox" style="font-size: 48px; color: #ccc; display: block; margin-bottom: 15px;"></i>
                                <h5 style="color: #999;">No Birth Certificates Found</h5>
                                <p style="color: #aaa;">There are no birth certificates available at the moment.</p>
                            </td>
                        </tr>
                        <?php
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
                  
<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- jQuery UI -->
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<!-- Bootstrap 4 -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Select2 -->
<script src="plugins/select2/js/select2.full.min.js"></script>
<!-- SweetAlert2 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/11.7.3/sweetalert2.all.min.js"></script>
<!-- DataTables & Plugins -->
<script src="plugins/datatables/jquery.dataTables.min.js"></script>
<script src="plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
<script src="plugins/datatables-buttons/js/dataTables.buttons.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.html5.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.print.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.colVis.min.js"></script>

<script>
    $(function() {
        // Initialize DataTable with enhanced features
        $('#example2').DataTable({
            "paging": true,
            "lengthChange": true,
            "searching": true,
            "ordering": true,
            "info": true,
            "autoWidth": false,
            "responsive": true,
            "pageLength": 10,
            "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            "order": [[0, "desc"]],
            "language": {
                "search": "Search:",
                "lengthMenu": "Show _MENU_ entries",
                "info": "Showing _START_ to _END_ of _TOTAL_ certificates",
                "infoEmpty": "Showing 0 to 0 of 0 certificates",
                "infoFiltered": "(filtered from _MAX_ total certificates)",
                "zeroRecords": "No matching certificates found",
                "emptyTable": "No birth certificates available",
                "paginate": {
                    "first": "First",
                    "last": "Last",
                    "next": "Next",
                    "previous": "Previous"
                }
            },
            "dom": "<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>>" +
                   "<'row'<'col-sm-12'tr>>" +
                   "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
            "columnDefs": [
                { "orderable": false, "targets": [3, 4] } // Disable sorting for action columns
            ]
        });
    });

    // Delete confirmation with SweetAlert2
    function deleteRecord(button) {
        const form = button.closest('form');
        
        Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this action!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="fas fa-trash"></i> Yes, delete it!',
            cancelButtonText: '<i class="fas fa-times"></i> Cancel',
            reverseButtons: true,
            customClass: {
                confirmButton: 'btn btn-danger btn-lg',
                cancelButton: 'btn btn-secondary btn-lg'
            },
            buttonsStyling: false
        }).then((result) => {
            if (result.isConfirmed) {
                // Show loading
                Swal.fire({
                    title: 'Deleting...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                // Submit the form
                form.submit();
            }
        });
    }

    // Alert message function
    function alertMessage(type, message) {
        if (type == 'error') {
            type = 'danger';
        }
        return "<div class='alert alert-" + type + " alert-dismissible fade show'> " +
               "<a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a> " +
               message + " </div>";
    }

    // Add smooth scrolling to top when paginating
    $('#example2').on('page.dt', function() {
        $('html, body').animate({
            scrollTop: $(".birth-list-container").offset().top - 20
        }, 300);
    });

    // Disable right-click on action buttons (optional security)
    $('.btn-action').on('contextmenu', function(e) {
        e.preventDefault();
    });
</script>

<?php 
include('userfooter.php');
?>