<?php
include '../inc/funtions.php';

if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'Super Admin') {
    $user_id = $_SESSION['user_id'];
    
    // Fetch counts using the correct column name: 'business_status'
    $status_query = "
        SELECT 
            COUNT(*) as total_business,
            SUM(CASE WHEN business_status = 'active' THEN 1 ELSE 0 END) as active_count,
            SUM(CASE WHEN business_status = 'inactive' THEN 1 ELSE 0 END) as inactive_count
        FROM businesses
    ";
    $result = Querydb($status_query);
    $counts = mysqli_fetch_assoc($result);

    $total = $counts['total_business'] ?? 0;
    $active = $counts['active_count'] ?? 0;
    $inactive = $counts['inactive_count'] ?? 0;
?>

<?php
// ... [Keep your existing PHP logic at the top] ...
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bactriz | Business Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="shortcut icon" href="../assets/images/favicon.png" type="image/x-icon">
    <link rel="stylesheet" href="../assets/vendors/simple-datatables/style.css">
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<div class="d-flex" id="wrapper">
    <div id="sidebar-wrapper">
        <div class="sidebar-heading border-bottom border-secondary">
            <i class="fa fa-shield-halved me-2"></i>Bactriz CRM
        </div>
        <div class="list-group list-group-flush mt-3">
            <a href="#" class="list-group-item active"><i class="fa fa-th-large me-3"></i>Dashboard</a>
            <a href="#" class="list-group-item"><i class="fa fa-building me-3"></i>Businesses</a>
            <a href="#" class="list-group-item"><i class="fa fa-users me-3"></i>User Management</a>
            <a href="#" class="list-group-item"><i class="fa fa-chart-line me-3"></i>Reports</a>
            <button type="submit" class="dropdown-item" id="authorize_sign_out"><i data-feather="log-out"></i> Logout</button>
        </div>
    </div>
    <div id="sidebar-overlay"></div>
    <div id="page-content-wrapper">
        <nav class="navbar navbar-expand-lg navbar-custom mb-4">
            <button id="menu-toggle"><i class="fa fa-bars"></i></button>
            <div class="container-fluid">
                <span class="navbar-text fw-semibold text-dark">
                    Welcome back, <?php echo $_SESSION['full_name']; ?> (Super Admin)
                </span>
                <div class="ms-auto d-flex align-items-center">
                    <!-- <div class="dropdown">
                        <?php 
                            // Check if image exists in session, otherwise use a default placeholder
                            $profile_pic = (!empty($_SESSION['profile_img'])) ? $_SESSION['profile_img'] : 'default-pic.png'; 
                        ?>
                        <img src="../assets/images/avatar/<?php echo $profile_pic; ?>" 
                             class="rounded-circle border profile-image" 
                             width="40" height="40" 
                             style="cursor:pointer; object-fit: cover;" 
                             data-bs-toggle="dropdown"> 
                        <ul class="dropdown-menu dropdown-menu-end shadow border-0 mt-2">
                            <li><a class="dropdown-item" href="profile.php"><i class="fa fa-user me-2 text-primary"></i>Profile</a></li>
                            <li><a class="dropdown-item" href="settings.php"><i class="fa fa-cog me-2 text-secondary"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="../logout.php"><i class="fa fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div> -->
                    <div class="dropdown">
                        <a href="#" data-bs-toggle="dropdown" class="nav-link dropdown-toggle nav-link-lg nav-link-user">
                            <div class="avatar me-1">
                                <img src="<?php echo !empty($_SESSION['profile_img']) ? 'assets/images/avatar/'. $_SESSION['profile_img'] : get_avatar($_SESSION['full_name']); ?>"class="rounded-circle" alt="Profile">
                            </div>                            
                        </a>
                        <div class="dropdown-menu dropdown-menu-end">
                            <a class="dropdown-item" href="user_profile.php"><i data-feather="user"></i> Account</a>
                            <a class="dropdown-item" href="user_profile.php"><i data-feather="settings"></i> Settings</a>
                            <div class="dropdown-divider"></div>
                            <button type="submit" class="dropdown-item" id="authorize_sign_out"><i data-feather="log-out"></i> Logout</button>
                        </div>
                    </div>
                </div>
            </div>
        </nav>

        <div class="container-fluid px-4">
            <div class="row mb-5 align-items-center">
                <div class="col">
                    <h2 class="fw-bold m-0">Business Directory</h2>
                    <p class="text-muted">Manage your business partners and system status</p>
                </div>
                <div class="col-auto text-end">
                    <button class="btn btn-white shadow-sm border" onclick="location.reload();">
                        <i class="fa fa-sync me-2"></i>Refresh Data
                    </button>
                </div>
            </div>

            <div class="row g-4 mb-5">
                <div class="col-md-4">
                    <div class="card stat-card bg-gradient-primary text-white p-3 shadow">
                        <div class="card-body d-flex align-items-center">
                            <div class="me-3 bg-white bg-opacity-25 p-3 rounded-circle">
                                <i class="fa fa-building fa-2x"></i>
                            </div>
                            <div>
                                <p class="mb-0 opacity-75">Total Business</p>
                                <h3 class="fw-bold mb-0"><?php echo $total; ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card stat-card bg-gradient-success text-white p-3 shadow">
                        <div class="card-body d-flex align-items-center">
                            <div class="me-3 bg-white bg-opacity-25 p-3 rounded-circle">
                                <i class="fa fa-check-double fa-2x"></i>
                            </div>
                            <div>
                                <p class="mb-0 opacity-75">Active Partners</p>
                                <h3 class="fw-bold mb-0"><?php echo $active; ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card stat-card bg-gradient-danger text-white p-3 shadow">
                        <div class="card-body d-flex align-items-center">
                            <div class="me-3 bg-white bg-opacity-25 p-3 rounded-circle">
                                <i class="fa fa-ban fa-2x"></i>
                            </div>
                            <div>
                                <p class="mb-0 opacity-75">Inactive Partners</p>
                                <h3 class="fw-bold mb-0"><?php echo $inactive; ?></h3>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card card-custom mb-5 overflow-hidden">
                <div class="row g-0">
                    <div class="col-md-4 bg-dark text-white p-5 d-flex flex-column justify-content-center">
                        <h4>Registration</h4>
                        <p class="opacity-50 small">Fill in the details to onboard a new business into the platform instantly.</p>
                    </div>
                    <div class="col-md-8 p-5">
                        <form id="addBusinessForm"> <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Business Name</label>
                                <input type="text" name="biz_name" class="form-control" placeholder="Enter name..." required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Business Email</label>
                                <input type="email" name="biz_email" class="form-control" placeholder="email@example.com" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Owner Name</label>
                                <input type="text" name="owner_name" class="form-control" placeholder="Full Name" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Owner Phone No</label>
                                <input type="text" name="owner_phone" class="form-control" placeholder="Phone Number" required>
                            </div>
                            <div class="col-md-12">
                                <label class="form-label fw-semibold">Owner Address</label>
                                <input type="text" name="owner_address" class="form-control" placeholder="Office Address" required>
                            </div>
                            <div class="col-12 mt-4 text-end">
                                <button type="button" id="saveBusinessBtn" class="btn btn-register px-5">
                                    <i class="fa fa-plus-circle me-2"></i>Add New Business
                                </button>
                            </div>
                        </div>
                    </form>
                    </div>
                </div>
            </div>

            <div class="card card-custom overflow-hidden">
                <div class="card-header bg-white p-4 border-0">
                    <h5 class="fw-bold m-0 text-dark">Recent Businesses</h5>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle" id="table1">
                        <thead>
                            <tr>
                                <th class="ps-4">ID</th>
                                <th>Business Detail</th>
                                <th>Status</th>
                                <th class="text-end pe-4">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $counts = 1;
                            $list = mysqli_query($conn, "SELECT * FROM businesses ORDER BY business_id DESC");
                            while($row = mysqli_fetch_assoc($list)) {

                            ?>
                            <tr>
                                <td class="ps-4 text-muted small">#<?php echo $counts; ?></td>
                                <td>
                                    <div class="fw-bold"><?php echo $row['business_name']; ?></div>
                                    <div class="text-muted small"><?php echo $row['business_email']; ?></div>
                                </td>
                                <td>
                                    <?php if($row['business_status'] == 'Active') { ?>
                                        <span class="status-badge bg-success-subtle text-success border border-success-subtle">
                                            <i class="fa fa-circle small me-1"></i> Active
                                        </span>
                                    <?php } else { ?>
                                        <span class="status-badge bg-secondary-subtle text-secondary border border-secondary-subtle">
                                            <i class="fa fa-circle-pause small me-1"></i> Inactive
                                        </span>
                                    <?php } ?>
                                </td>
                                <td class="text-end pe-4">
                                    <div class="btn-group">
                                        <button class="btn btn-light btn-sm border view-business" 
                                                data-id="<?php echo $row['business_id']; ?>" 
                                                title="View Details">
                                            <i class="fa fa-eye text-primary"></i>
                                        </button>

                                        <button class="btn btn-light btn-sm border edit-business-btn" data-id="<?php echo $row['business_id']; ?>">
                                            <i class="fa fa-edit text-warning"></i>
                                        </button>

                                        <button class="btn btn-light btn-sm border toggle-status" 
                                                data-id="<?php echo $row['business_id']; ?>" 
                                                data-current="<?php echo $row['business_status']; ?>"
                                                title="Toggle Status">
                                            <i class="fa fa-retweet"></i>
                                        </button>
                                        <button class="btn btn-light btn-sm border resend-activation" 
                                                data-id="<?php echo $row['business_id']; ?>" 
                                                data-email="<?php echo $row['business_email']; ?>"
                                                title="Resend Activation Link">
                                            <i class="fa fa-paper-plane text-info"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php $counts++; } ?>
                        </tbody>
                    </table>
                    <div class="modal fade" id="editBusinessModal" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content border-0 shadow">
                                <div class="modal-header bg-dark text-white">
                                    <h5 class="modal-title">Edit Business Details</h5>
                                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <form id="editBusinessForm">
                                    <div class="modal-body p-4">
                                        <input type="hidden" name="business_id" id="edit_biz_id">
                                        <div class="row g-3">
                                            <div class="col-12">
                                                <label class="form-label fw-bold">Business Name</label>
                                                <input type="text" name="biz_name" id="edit_biz_name" class="form-control" required>
                                            </div>
                                            <div class="col-12">
                                                <label class="form-label fw-bold">Business Email</label>
                                                <input type="email" name="biz_email" id="edit_biz_email" class="form-control" readonly>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label fw-bold">Owner Name</label>
                                                <input type="text" name="owner_name" id="edit_owner_name" class="form-control" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label fw-bold">Owner Phone</label>
                                                <input type="text" name="owner_phone" id="edit_owner_phone" class="form-control" required>
                                            </div>
                                            <div class="col-12">
                                                <label class="form-label fw-bold">Address</label>
                                                <textarea name="owner_address" id="edit_owner_address" class="form-control" rows="2"></textarea>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="modal-footer border-0">
                                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                                        <button type="submit" class="btn btn-dark px-4">Save Changes</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
    </div>
</div>
<script src="../assets/vendors/jquery/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../assets/vendors/sweetalert/sweetalert.js"></script>
<script src="../assets/vendors/simple-datatables/simple-datatables.js"></script>
<script>
    $(document).ready(function() {
        $("#menu-toggle").on("click", function(e) {
            e.preventDefault();
            $("#wrapper").toggleClass("toggled");
        });

        // Optional: Close sidebar when clicking a link on mobile
        if ($(window).width() <= 768) {
            $("#sidebar-wrapper .list-group-item").on("click", function() {
                $("#wrapper").removeClass("toggled");
            });
        }
    });

    document.querySelectorAll('table[id^="table"]').forEach(table => {
        new simpleDatatables.DataTable(table, {
            searchable: true,
            fixedHeight: false,
            perPage: 10
        });
    });

    $('#saveBusinessBtn').on('click', function() {
        let form = $('#addBusinessForm');
        Swal.fire({
            title: 'Processing...',
            text: 'Registering business into the system',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });

        // Send Data via AJAX
        $.ajax({
            url: '../inc/code_query.php',
            type: 'POST',
            data: form.serialize() + '&action=add_business',
            success: function(response) {
                if (response.trim() === "success") {
                    Swal.fire({
                        icon: 'success',
                        title: 'Onboarded!',
                        text: 'The business has been successfully registered.',
                        confirmButtonColor: '#334155'
                    }).then(() => {
                        location.reload(); // Refresh to see the new business in the table
                    });
                } else {
                    Swal.fire('Error', 'Could not register business: ' + response, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Network connection failed.', 'error');
            }
        });
    });

    $(document).on('click', '.view-business', function() {
        let bizId = $(this).data('id');

        // Fetch data using AJAX
        $.ajax({
            url: '../inc/code_query.php',
            type: 'GET',
            data: { id: bizId },
            dataType: 'json',
            success: function(data) {
                Swal.fire({
                    title: '<strong>Business Details</strong>',
                    icon: 'info',
                    html: `
                        <div class="text-start border-top pt-3">
                            <p><strong>Business:</strong> ${data.business_name}</p>
                            <p><strong>Email:</strong> ${data.business_email}</p>
                            <hr>
                            <p><strong>Owner:</strong> ${data.business_owner}</p>
                            <p><strong>Phone:</strong> ${data.business_phone}</p>
                            <p><strong>Address:</strong> ${data.business_address}</p>
                        </div>
                    `,
                    showCloseButton: true,
                    confirmButtonColor: '#334155'
                });
            }
        });
    });

    $(document).on('click', '.resend-activation', function() {
        let bizId = $(this).data('id');
        let currentEmail = $(this).data('email');

        Swal.fire({
            title: 'Resend Activation',
            text: 'Confirm or update the email address below:',
            input: 'email', // Validates email format automatically
            inputValue: currentEmail,
            showCancelButton: true,
            confirmButtonColor: '#334155',
            confirmButtonText: 'Update & Send',
            inputValidator: (value) => {
                if (!value) {
                    return 'You need to write a valid email!';
                }
            }
        }).then((result) => {
            if (result.isConfirmed) {
                let newEmail = result.value; // Captures the email from the input

                Swal.fire({
                    title: 'Processing...',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                });

                $.ajax({
                    url: '../inc/code_query.php',
                    type: 'POST',
                    data: { 
                        action: 'resend_activation', 
                        business_id: bizId,
                        new_email: newEmail // Pass the potentially new email
                    },
                    success: function(response) {
                        if (response.trim() === "success") {
                            Swal.fire('Sent!', `Link sent to ${newEmail}`, 'success')
                            .then(() => { location.reload(); }); // Reload to show new email in table
                        } else {
                            Swal.fire('Error', response, 'error');
                        }
                    }
                });
            }
        });
    });

    // FETCH DATA INTO MODAL
    $(document).on('click', '.edit-business-btn', function() {
        let bizId = $(this).data('id');

        $.ajax({
            url: '../inc/code_query.php',
            type: 'GET',
            data: { id: bizId },
            dataType: 'json',
            success: function(data) {
                $('#edit_biz_id').val(data.business_id);
                $('#edit_biz_name').val(data.business_name);
                $('#edit_biz_email').val(data.business_email);
                $('#edit_owner_name').val(data.business_owner);
                $('#edit_owner_phone').val(data.business_phone);
                $('#edit_owner_address').val(data.business_address);
                
                $('#editBusinessModal').modal('show');
            }
        });
    });

    // SUBMIT UPDATED DATA
    $('#editBusinessForm').on('submit', function(e) {
        e.preventDefault();
        
        Swal.fire({
            title: 'Saving Changes...',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });

        $.ajax({
            url: '../inc/code_query.php',
            type: 'POST',
            data: $(this).serialize() + '&action=update_business',
            success: function(response) {
                if(response.trim() === "success") {
                    Swal.fire({
                        icon: 'success',
                        title: 'Record Updated',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload(); 
                    });
                } else {
                    Swal.fire('Error', response, 'error');
                }
            }
        });
    });

    $(document).on('click', '.toggle-status', function() {
        let btn = $(this);
        let bizId = btn.data('id');
        let currentStatus = btn.data('current');
        let newStatus = (currentStatus === 'active') ? 'inactive' : 'active';

        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');

        $.ajax({
            url: '../inc/code_query.php',
            type: 'POST',
            data: { id: bizId, status: newStatus, 'action': 'ChengeStatus' },
            success: function(response) {
                if(response.trim() === "success") {
                    btn.data('current', newStatus);
                    btn.prop('disabled', false).html('<i class="fa fa-retweet me-1"></i>');

                    let row = btn.closest('tr');
                    let badge = row.find('.status-badge');
                    let resendBtn = row.find('.resend-activation');

                    if(newStatus === 'active') {
                        // Update Badge to Active
                        badge.removeClass('bg-secondary-subtle text-secondary border-secondary-subtle')
                             .addClass('bg-success-subtle text-success border-success-subtle')
                             .html('<i class="fa fa-circle small me-1"></i> Active');
                        
                        // Disable Resend Button (User is already active)
                        resendBtn.prop('disabled', true).addClass('text-muted').removeClass('text-info');
                    } else {
                        // Update Badge to Inactive
                        badge.removeClass('bg-success-subtle text-success border-success-subtle')
                             .addClass('bg-secondary-subtle text-secondary border-secondary-subtle')
                             .html('<i class="fa fa-circle-pause small me-1"></i> Inactive');
                        
                        // Enable Resend Button (User needs activation again)
                        resendBtn.prop('disabled', false).removeClass('text-muted').addClass('text-info');
                    }
                } else {
                    Swal.fire('Error', response, 'error');
                    btn.prop('disabled', false).html('<i class="fa fa-retweet me-1"></i>');
                }
            }
        });
    });
    $(document).ready(function(){
        $('#authorize_sign_out').click(function (e){
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "../inc/code_query.php",
                data: { action: 'authorize_sign_out' },
                success: function(response) {
                    Swal.fire({
                    title: "Logout",
                    icon: "success"
                    }).then(() => {
                        window.location.href = 'auth-login.html';
                    });         
                }
            });
        });
    });
</script>
</body>
</html>

<?php 
} else {
    header('Location: ../auth-login.html');
    exit;
}
?>