<?php
session_start(); // Start the session
// Include the database connection file
include 'layouts/dbconn.php';

// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php'); // Redirect to the login page
    exit();
}

// Query to fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
} else {
    // Handle the case if user details are not found
}

// Get corporate statistics
$sql_total = "SELECT COUNT(*) as total FROM corporate";
$result_total = $conn->query($sql_total);
$total_corporates = $result_total->fetch_assoc()['total'];

// Get active corporates
$sql_active = "SELECT COUNT(*) as active FROM corporate WHERE cancelled = 0";
$result_active = $conn->query($sql_active);
$active_corporates = $result_active->fetch_assoc()['active'];

// Get cancelled corporates
$sql_cancelled = "SELECT COUNT(*) as cancelled FROM corporate WHERE cancelled = 1";
$result_cancelled = $conn->query($sql_cancelled);
$cancelled_corporates = $result_cancelled->fetch_assoc()['cancelled'];

// Get this month's new corporates
$sql_new = "SELECT 
    COUNT(*) as new_corps,
    ROUND(((COUNT(*) - LAG(COUNT(*)) OVER (ORDER BY MONTH(date_entered)))
    / LAG(COUNT(*)) OVER (ORDER BY MONTH(date_entered)) * 100), 2) as growth_rate
FROM corporate 
WHERE MONTH(date_entered) = MONTH(CURRENT_DATE())
    AND YEAR(date_entered) = YEAR(CURRENT_DATE())";
$result_new = $conn->query($sql_new);
$new_corps_data = $result_new->fetch_assoc();

// Close the connection (optional, can leave open for further queries in the same script)
// $conn->close();
?>
<?php include 'layouts/main.php'; ?>

<head>

    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Corporate List')); ?>

    <!-- Sweet Alert css-->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />

    <?php include 'layouts/head-css.php'; ?>

</head>

<body>

    <!-- Begin page -->
    <div id="layout-wrapper">

        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">

            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Corporates', 'title' => 'Corporate List')); ?>

                    <div class="row">
    <div class="col-xxl-3 col-sm-6">
        <div class="card card-animate">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <p class="fw-semibold text-muted mb-0">Total Corporates</p>
                        <h2 class="mt-4 ff-secondary fw-semibold">
                            <span class="counter-value" data-target="<?php echo $total_corporates; ?>">0</span>
                        </h2>
                        <p class="mb-0 text-muted">
                            <span class="badge bg-light text-success mb-0">
                                <i class="ri-arrow-up-line align-middle"></i> 
                                <?php echo $new_corps_data['growth_rate'] ?? 0; ?>%
                            </span> 
                            vs. previous month
                        </p>
                    </div>
                    <div>
                        <div class="avatar-sm flex-shrink-0">
                            <span class="avatar-title bg-primary-subtle text-primary rounded-circle fs-4">
                                <i class="ri-building-line"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xxl-3 col-sm-6">
        <div class="card card-animate">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <p class="fw-semibold text-muted mb-0">New Corporates</p>
                        <h2 class="mt-4 ff-secondary fw-semibold">
                            <span class="counter-value" data-target="<?php echo $new_corps_data['new_corps'] ?? 0; ?>">0</span>
                        </h2>
                        <p class="mb-0 text-muted">
                            <span class="badge bg-light text-info mb-0">
                                <i class="ri-arrow-up-line align-middle"></i> This Month
                            </span>
                        </p>
                    </div>
                    <div>
                        <div class="avatar-sm flex-shrink-0">
                            <span class="avatar-title bg-info-subtle text-info rounded-circle fs-4">
                                <i class="ri-add-circle-line"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xxl-3 col-sm-6">
        <div class="card card-animate">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <p class="fw-semibold text-muted mb-0">Active Corporates</p>
                        <h2 class="mt-4 ff-secondary fw-semibold">
                            <span class="counter-value" data-target="<?php echo $active_corporates; ?>">0</span>
                        </h2>
                        <p class="mb-0 text-muted">
                            <span class="badge bg-light text-success mb-0">
                                <i class="ri-check-line align-middle"></i> Currently Active
                            </span>
                        </p>
                    </div>
                    <div>
                        <div class="avatar-sm flex-shrink-0">
                            <span class="avatar-title bg-success-subtle text-success rounded-circle fs-4">
                                <i class="ri-checkbox-circle-line"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xxl-3 col-sm-6">
        <div class="card card-animate">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <p class="fw-semibold text-muted mb-0">Cancelled Corporates</p>
                        <h2 class="mt-4 ff-secondary fw-semibold">
                            <span class="counter-value" data-target="<?php echo $cancelled_corporates; ?>">0</span>
                        </h2>
                        <p class="mb-0 text-muted">
                            <span class="badge bg-light text-danger mb-0">
                                <i class="ri-close-circle-line align-middle"></i> Total Cancelled
                            </span>
                        </p>
                    </div>
                    <div>
                        <div class="avatar-sm flex-shrink-0">
                            <span class="avatar-title bg-danger-subtle text-danger rounded-circle fs-4">
                                <i class="ri-delete-bin-line"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
                    <!--end row-->

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card" id="ticketsList">
                                <div class="card-header border-0">
                                    <div class="d-flex align-items-center">
                                        <h5 class="card-title mb-0 flex-grow-1">Corporates</h5>
                                        <div class="flex-shrink-0">
                                            <div class="d-flex flex-wrap gap-2">
                                            	<a href="add_new_corporate.php" class="btn btn-primary add-btn">
                                                    <i class="ri-add-line align-bottom me-1"></i> Create Corporate
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body border border-dashed border-end-0 border-start-0">
                                   <form>
                                        <div class="row g-3">
                                            <div class="col-xxl-5 col-sm-12">
                                                <div class="search-box">
                                                    <input type="text" class="form-control search bg-light border-light" id="searchCorporate" placeholder="Search for corporate...">
                                                    <i class="ri-search-line search-icon"></i>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                                <!--end card-body-->
                                <div class="card-body">
                                    <div class="table-responsive table-card mb-4">
                                        <table class="table align-middle table-nowrap mb-0" id="ticketTable">
                                            <thead>
                                                <tr>
                                                    <th scope="col" style="width: 40px;">
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" id="checkAll" value="option">
                                                        </div>
                                                    </th>
                                                    <th class="sort" data-sort="id">ID</th>
                                                    <th class="sort" data-sort="tasks_name">Corporate</th>
                                                    <th class="sort" data-sort="client_name">Scheme</th>
                                                    <th class="sort" data-sort="assignedto">Policy No</th>
                                                    <th class="sort" data-sort="create_date">Created Date</th>
                                                    <th class="sort" data-sort="status">Status</th>
                                                    <th class="sort" data-sort="priority">User</th>
                                                    <th class="sort" data-sort="action">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody class="list form-check-all" id="ticket-list-data">
                                                <?php
                                                include 'layouts/dbconn.php';
                                                
                                                $sql = "SELECT 
                                                    c.corp_id,
                                                    c.corporate,
                                                    c.scheme,
                                                    c.policy_no,
                                                    c.date_entered,
                                                    CASE 
                                                        WHEN c.cancelled = 1 THEN 'Cancelled'
                                                        WHEN c.cancelled = 0 THEN 'Active'
                                                        ELSE 'Pending'
                                                    END as status,
                                                    u.username as user_name
                                                FROM corporate c
                                                LEFT JOIN users u ON c.user_id = u.username
                                                ORDER BY c.date_entered DESC";
                                                
                                                $result = $conn->query($sql);
                                                
                                                $output = '';
                                                if ($result->num_rows > 0) {
                                                    while($row = $result->fetch_assoc()) {
                                                        $statusClass = '';
                                                        switch($row['status']) {
                                                            case 'Active':
                                                                $statusClass = 'bg-success';
                                                                break;
                                                            case 'Cancelled':
                                                                $statusClass = 'bg-danger';
                                                                break;
                                                            default:
                                                                $statusClass = 'bg-warning';
                                                                break;
                                                        }

                                                        // Build menu items based on status
                                                        $menuItems = '';
                                                        $menuItems .= '
                                                            <li>
                                                                <a class="dropdown-item" href="view_corporate_details.php?id=' . $row['corp_id'] . '">
                                                                    <i class="ri-eye-fill align-bottom me-2 text-muted"></i> View
                                                                </a>
                                                            </li>
                                                            <li>
                                                                <a class="dropdown-item" href="edit_corporate.php?id=' . $row['corp_id'] . '">
                                                                    <i class="ri-pencil-fill align-bottom me-2 text-muted"></i> Edit
                                                                </a>
                                                            </li>';

                                                        // Add status-specific actions
                                                        if ($row['status'] == 'Active') {
                                                            $menuItems .= '
                                                                <li>
                                                                    <a class="dropdown-item" href="javascript:void(0);" onclick="suspendCorporate(\'' . htmlspecialchars($row['corp_id']) . '\')">
                                                                        <i class="ri-pause-circle-fill align-bottom me-2 text-warning"></i> Suspend
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item" href="javascript:void(0);" onclick="terminateCorporate(\'' . htmlspecialchars($row['corp_id']) . '\')">
                                                                        <i class="ri-stop-circle-fill align-bottom me-2 text-danger"></i> Terminate
                                                                    </a>
                                                                </li>';
                                                        } elseif ($row['status'] == 'Suspended' || $row['status'] == 'Cancelled') {
                                                            $menuItems .= '
                                                                <li>
                                                                    <a class="dropdown-item" href="javascript:void(0);" onclick="reinstateCorporate(\'' . htmlspecialchars($row['corp_id']) . '\')">
                                                                        <i class="ri-restart-line align-bottom me-2 text-success"></i> Reinstate
                                                                    </a>
                                                                </li>';
                                                        }

                                                        // Add delete option for all statuses
                                                        $menuItems .= '
                                                            <li>
                                                                <a class="dropdown-item text-danger" href="javascript:void(0);" onclick="deleteCorporate(\'' . htmlspecialchars($row['corp_id']) . '\')">
                                                                    <i class="ri-delete-bin-fill align-bottom me-2 text-danger"></i> Delete
                                                                </a>
                                                            </li>';
                                                
                                                        $output .= '
                                                        <tr>
                                                            <th scope="row">
                                                                <div class="form-check">
                                                                    <input class="form-check-input" type="checkbox" name="checkAll" value="' . $row['corp_id'] . '">
                                                                </div>
                                                            </th>
                                                            <td class="id">' . htmlspecialchars($row['corp_id']) . '</td>
                                                            <td class="tasks_name">' . htmlspecialchars($row['corporate']) . '</td>
                                                            <td class="client_name">' . htmlspecialchars($row['scheme']) . '</td>
                                                            <td class="assignedto">' . htmlspecialchars($row['policy_no']) . '</td>
                                                            <td class="create_date">' . date('d M, Y', strtotime($row['date_entered'])) . '</td>
                                                            <td class="status"><span class="badge ' . $statusClass . '">' . $row['status'] . '</span></td>
                                                            <td class="priority">' . htmlspecialchars($row['user_name']) . '</td>
                                                            <td class="action">
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="ri-more-fill align-middle"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                                        ' . $menuItems . '
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>';
                                                    }
                                                } else {
                                                    $output .= '<tr><td colspan="9" class="text-center">No records found</td></tr>';
                                                }
                                                
                                                echo $output;
                                                $conn->close();
                                                ?>
                                            </tbody>
                                        </table>
                                        <div class="noresult" style="display: none">
                                            <div class="text-center">
                                                <lord-icon src="https://cdn.lordicon.com/msoeawqm.json" trigger="loop" colors="primary:#121331,secondary:#08a88a" style="width:75px;height:75px"></lord-icon>
                                                <h5 class="mt-2">Sorry! No Result Found</h5>
                                                <p class="text-muted mb-0">We've searched more than 150+ Tickets We did not find any Tickets for you search.</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex justify-content-end mt-2">
                                        <div class="pagination-wrap hstack gap-2">
                                            <a class="page-item pagination-prev disabled" href="#">
                                                Previous
                                            </a>
                                            <ul class="pagination listjs-pagination mb-0"></ul>
                                            <a class="page-item pagination-next" href="#">
                                                Next
                                            </a>
                                        </div>
                                    </div>

                                   
                                </div>
                                <!--end card-body-->
                            </div>
                            <!--end card-->
                        </div>
                        <!--end col-->
                    </div>
                    <!--end row-->

                    

                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->

    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>

    <!-- list.js min js -->
    <script src="assets/libs/list.js/list.min.js"></script>

    <!--list pagination js-->
    <script src="assets/libs/list.pagination.js/list.pagination.min.js"></script>

    <!-- titcket init js -->
 

    <!-- Sweet Alerts js -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <!-- App js -->
    <script src="assets/js/app.js"></script>
    <script>
        // Add this to your existing JavaScript file or in a script tag
    $(document).ready(function() {
        // Load corporate list on page load
        loadCorporateList();
    
        // Checkbox functionality
        $("#checkAll").on("change", function() {
            $(".form-check-input").prop('checked', $(this).prop("checked"));
        });
    
        // Search functionality if needed
        $("#searchInput").on("keyup", function() {
            var value = $(this).val().toLowerCase();
            $("#ticket-list-data tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
            });
        });
    });

function loadCorporateList() {
    // Add a loading indicator if needed
    $('#corporateListContainer').html('<div class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading...</div>');
    
    // Reload the corporate list
    $.ajax({
        url: 'fetch_corporate.php', // Adjust this to your actual URL
        type: 'GET',
        success: function(response) {
            $('#corporateListContainer').html(response);
        },
        error: function(xhr, status, error) {
            console.error("Error loading corporate list:", error);
            $('#corporateListContainer').html('<div class="alert alert-danger">Error loading corporate list</div>');
        }
    });
}

// Add these functions to your existing JavaScript
function suspendCorporate(corpId) {
    Swal.fire({
        title: 'Suspend Corporate',
        text: 'This will suspend all operations for this corporate. Please provide a reason:',
        input: 'textarea',
        inputAttributes: {
            required: true,
            placeholder: 'Enter reason for suspension'
        },
        showCancelButton: true,
        confirmButtonText: 'Suspend',
        showLoaderOnConfirm: true,
        preConfirm: (reason) => {
            if (!reason) {
                Swal.showValidationMessage('Please enter a reason for suspension');
                return false;
            }
            return $.ajax({
                url: 'update_corporate_status.php',
                type: 'POST',
                data: {
                    corp_id: corpId,
                    action: 'suspend',
                    reason: reason
                }
            }).catch(error => {
                Swal.showValidationMessage(`Request failed: ${error.responseText}`);
            });
        },
        allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Success!',
                text: 'Corporate has been suspended',
                icon: 'success'
            }).then(() => {
                window.location.reload();
            });
        }
    });
}

function terminateCorporate(corpId) {
    Swal.fire({
        title: 'Terminate Corporate',
        text: 'This will terminate this corporate scheme. All benefits will be terminated. Please provide a reason:',
        input: 'textarea',
        inputAttributes: {
            required: true,
            placeholder: 'Enter reason for termination'
        },
        showCancelButton: true,
        confirmButtonText: 'Terminate',
        confirmButtonColor: '#dc3545',
        showLoaderOnConfirm: true,
        preConfirm: (reason) => {
            if (!reason) {
                Swal.showValidationMessage('Please enter a reason for termination');
                return false;
            }
            return $.ajax({
                url: 'update_corporate_status.php',
                type: 'POST',
                data: {
                    corp_id: corpId,
                    action: 'terminate',
                    reason: reason
                }
            }).catch(error => {
                Swal.showValidationMessage(`Request failed: ${error.responseText}`);
            });
        },
        allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Success!',
                text: 'Corporate has been terminated',
                icon: 'success'
            }).then(() => {
                window.location.reload();
            });
        }
    });
}

function reinstateCorporate(corpId) {
    Swal.fire({
        title: 'Reinstate Corporate',
        text: 'This will reinstate this corporate and reactivate all benefits. Please provide a reason:',
        input: 'textarea',
        inputAttributes: {
            required: true,
            placeholder: 'Enter reason for reinstatement'
        },
        showCancelButton: true,
        confirmButtonText: 'Reinstate',
        confirmButtonColor: '#28a745',
        showLoaderOnConfirm: true,
        preConfirm: (reason) => {
            if (!reason) {
                Swal.showValidationMessage('Please enter a reason for reinstatement');
                return false;
            }
            return $.ajax({
                url: 'update_corporate_status.php',
                type: 'POST',
                data: {
                    corp_id: corpId,
                    action: 'reinstate',
                    reason: reason
                }
            }).catch(error => {
                Swal.showValidationMessage(`Request failed: ${error.responseText}`);
            });
        },
        allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Success!',
                text: 'Corporate has been reinstated',
                icon: 'success'
            }).then(() => {
                window.location.reload();
            });
        }
    });
}

// Update the existing deleteCorporate function for soft delete
function deleteCorporate(corpId) {
    Swal.fire({
        title: 'Delete Corporate',
        text: 'This corporate record will be marked as deleted but can be recovered by an administrator. Continue?',
        icon: 'warning',
        input: 'textarea',
        inputAttributes: {
            required: true,
            placeholder: 'Enter reason for deletion'
        },
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        confirmButtonText: 'Delete',
        showLoaderOnConfirm: true,
        preConfirm: (reason) => {
            if (!reason) {
                Swal.showValidationMessage('Please enter a reason for deletion');
                return false;
            }
            return $.ajax({
                url: 'delete_corporate.php',
                type: 'POST',
                data: {
                    corp_id: corpId,
                    reason: reason
                }
            }).catch(error => {
                Swal.showValidationMessage(`Request failed: ${error.responseText}`);
            });
        },
        allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Deleted!',
                text: 'Corporate has been deleted',
                icon: 'success'
            }).then(() => {
                window.location.reload();
            });
        }
    });
}
    </script>
    <script>
$(document).ready(function(){
    let searchTimer;
    const searchInput = $('#searchCorporate');
    
    searchInput.on('keyup', function(){
        clearTimeout(searchTimer); // Clear the previous timer
        
        // Get the search value
        const searchValue = $(this).val();
        
        // Set a new timer
        searchTimer = setTimeout(function() {
            // Show loading indicator in the table
            $('#ticket-list-data').html('<tr><td colspan="9" class="text-center"><i class="fas fa-spinner fa-spin"></i> Searching...</td></tr>');
            
            // Make the AJAX call
            $.ajax({
                url: 'search_corporate.php',
                type: 'POST',
                data: { search: searchValue },
                success: function(response) {
                    $('#ticket-list-data').html(response);
                    
                    // Reinitialize tooltips if you're using Bootstrap tooltips
                    $('[data-bs-toggle="tooltip"]').tooltip();
                },
                error: function(xhr, status, error) {
                    console.error("Search Error:", error);
                    $('#ticket-list-data').html('<tr><td colspan="9" class="text-center text-danger">Error occurred while searching</td></tr>');
                }
            });
        }, 500); // Wait 500ms after user stops typing before searching
    });
});
</script>
</body>

</html>