<?php
session_start();
include 'layouts/dbconn.php';
require_once 'ClientDebtController.php';

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

// Create client debt controller
$debtController = new ClientDebtController($conn);

// Get user details for permission checks
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id 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'];
    $role_id = $row_user_details['role_id'];
}

// Function to check user permissions
function hasPermission($role_id, $permission) {
    // Define permissions for different roles
    $permissions = [
        '1' => ['view', 'edit', 'delete', 'approve', 'invoice'], // Admin has all permissions
        '2' => ['view', 'edit', 'approve', 'invoice'], // General Manager
        '3' => ['view', 'edit', 'invoice'], // Operations
        '4' => ['view', 'invoice'], // Finance
        '5' => ['view', 'edit'], // Declaration Officer
        '6' => ['view'], // Shipping Line Clerk
        '7' => ['view'], // Transport Supervisor
    ];
    
    if (isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id])) {
        return true;
    }
    
    return false;
}

// Check if user has permission to view and edit client debts
$can_view = hasPermission($role_id, 'view');
$can_edit = hasPermission($role_id, 'edit') || hasPermission($role_id, 'approve');

if (!$can_view) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

// Handle search and filter parameters
$currency = isset($_GET['currency']) ? $_GET['currency'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}

// Get all customers with their debt totals
$customerDebts = $debtController->getAllCustomerDebts($currency);

// Filter by search term if provided
if (!empty($search)) {
    $filteredDebts = [];
    foreach ($customerDebts as $customer) {
        if (
            stripos($customer['first_name'], $search) !== false ||
            stripos($customer['last_name'], $search) !== false ||
            stripos($customer['phone_number'], $search) !== false ||
            stripos($customer['email'], $search) !== false
        ) {
            $filteredDebts[] = $customer;
        }
    }
    $customerDebts = $filteredDebts;
}

// Get distinct currencies for filtering
$currencies = [];
$sql_currencies = "SELECT DISTINCT currency FROM client_debts ORDER BY currency";
$result_currencies = $conn->query($sql_currencies);
if ($result_currencies && $result_currencies->num_rows > 0) {
    while ($row = $result_currencies->fetch_assoc()) {
        $currencies[] = $row['currency'];
    }
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Client Debt Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="assets/libs/datatables/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/datatables/buttons.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/datatables/responsive.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .debt-badge {
            font-size: 0.9rem;
            padding: 5px 8px;
        }
        .debt-badge.positive {
            background-color: #f46a6a;
            color: white;
        }
        .debt-badge.negative {
            background-color: #34c38f;
            color: white;
        }
        .debt-badge.zero {
            background-color: #74788d;
            color: white;
        }
        .filters-container {
            margin-bottom: 20px;
        }
        .search-box {
            position: relative;
        }
        .search-box .form-control {
            padding-left: 40px;
        }
        .search-box .search-icon {
            position: absolute;
            left: 13px;
            top: 50%;
            transform: translateY(-50%);
            color: #74788d;
        }
        .action-btn {
            margin-right: 5px;
        }
    </style>
</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' => 'Finance Management', 'title' => 'Client Debt Management')); ?>

                    <?php
                    // Show success message if set
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">';
                        echo $_SESSION['success_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['success_message']);
                    }
                    
                    // Show error message if set
                    if (isset($_SESSION['error_message'])) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $_SESSION['error_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['error_message']);
                    }
                    ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">Client Debt Summary</h5>
                                    <div>
                                        <?php if ($can_edit): ?>
                                        <a href="debt_adjustment.php" class="btn btn-primary btn-sm">
                                            <i class="ri-add-line align-bottom"></i> Add Adjustment
                                        </a>
                                        <?php endif; ?>
                                        <!--<a href="credit_note_list.php" class="btn btn-info btn-sm ms-2">
                                            <i class="ri-file-list-3-line align-bottom"></i> Credit Notes
                                        </a>
                                        <a href="debit_note_list.php" class="btn btn-warning btn-sm ms-2">
                                            <i class="ri-file-list-3-line align-bottom"></i> Debit Notes
                                        </a> -->
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="filters-container">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <form action="" method="GET" class="d-flex">
                                                    <div class="search-box flex-grow-1 me-2">
                                                        <input type="text" name="search" class="form-control search" placeholder="Search client name, phone, email..." value="<?php echo htmlspecialchars($search); ?>">
                                                        <i class="ri-search-line search-icon"></i>
                                                    </div>
                                                    <button type="submit" class="btn btn-primary">Search</button>
                                                </form>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="d-flex justify-content-md-end">
                                                    <select class="form-select w-auto" id="currency-filter" onchange="filterByCurrency(this.value)">
                                                        <option value="">All Currencies</option>
                                                        <?php foreach ($currencies as $curr): ?>
                                                        <option value="<?php echo $curr; ?>" <?php echo ($curr == $currency) ? 'selected' : ''; ?>>
                                                            <?php echo $curr; ?>
                                                        </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="table-responsive">
                                        <table id="debt-table" class="table table-bordered dt-responsive nowrap table-striped align-middle" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>Client</th>
                                                    <th>Contact</th>
                                                    <th>Email</th>
                                                    <th>Currency</th>
                                                    <th>Total Debt</th>
                                                    <th>Credit Limit</th>
                                                    <th>Last Updated</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                if (!empty($customerDebts)) {
                                                    foreach ($customerDebts as $debt) {
                                                        $customerId = $debt['customer_id'];
                                                        $customerName = $debt['first_name'] . ' ' . $debt['last_name'];
                                                        $phone = $debt['phone_number'] ?? 'N/A';
                                                        $email = $debt['email'] ?? 'N/A';
                                                        $currency = $debt['currency'] ?? '';
                                                        $totalDebt = $debt['total_debt'] ?? 0;
                                                        $creditLimit = $debt['credit_limit'] ?? null;
                                                        $lastUpdated = $debt['last_updated'] ?? 'N/A';
                                                        
                                                        // Determine badge class for debt
                                                        $debtBadgeClass = 'zero';
                                                        if ($totalDebt > 0) {
                                                            $debtBadgeClass = 'positive';
                                                        } elseif ($totalDebt < 0) {
                                                            $debtBadgeClass = 'negative';
                                                        }
                                                        
                                                        // Format last updated date
                                                        $formattedDate = $lastUpdated !== 'N/A' ? date('Y-m-d H:i', strtotime
                                                        ($lastUpdated)) : 'N/A';
                                                        
                                                        echo "<tr>";
                                                        echo "<td><a href='view_customer.php?id={$customerId}'>{$customerName}</a></td>";
                                                        echo "<td>{$phone}</td>";
                                                        echo "<td>{$email}</td>";
                                                        echo "<td>{$currency}</td>";
                                                        echo "<td><span class='badge debt-badge {$debtBadgeClass}'>{$currency} " . number_format($totalDebt, 2) . "</span></td>";
                                                        
                                                        // Credit limit column
                                                        if ($creditLimit !== null) {
                                                            echo "<td>{$currency} " . number_format($creditLimit, 2) . "</td>";
                                                        } else {
                                                            echo "<td>Not set</td>";
                                                        }
                                                        
                                                        echo "<td>{$formattedDate}</td>";
                                                        
                                                        // Action buttons
                                                        echo "<td>";
                                                        echo "<a href='view_client_debt.php?id={$customerId}&currency={$currency}' class='btn btn-sm btn-info action-btn' title='View Transactions'><i class='ri-eye-line'></i></a>";
                                                        
                                                        if ($can_edit) {
                                                            echo "<a href='debt_adjustment.php?customer_id={$customerId}&currency={$currency}' class='btn btn-sm btn-primary action-btn' title='Add Adjustment'><i class='ri-add-line'></i></a>";
                                                            
                                                            echo "<a href='create_credit_note.php?customer_id={$customerId}&currency={$currency}' class='btn btn-sm btn-success action-btn' title='Create Credit Note'><i class='ri-file-reduce-line'></i></a>";
                                                            
                                                            echo "<a href='create_debit_note.php?customer_id={$customerId}&currency={$currency}' class='btn btn-sm btn-warning action-btn' title='Create Debit Note'><i class='ri-file-add-line'></i></a>";
                                                        }
                                                        
                                                        echo "</td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='8' class='text-center'>No client debt records found</td></tr>";
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Summary Cards -->
                    <div class="row">
                        <?php
                        // Calculate summary statistics
                        $totalOutstanding = [];
                        $totalCustomersWithDebt = [];
                        $overLimitCustomers = [];
                        
                        foreach ($customerDebts as $debt) {
                            $currency = $debt['currency'];
                            $debtAmount = $debt['total_debt'] ?? 0;
                            $creditLimit = $debt['credit_limit'] ?? 0;
                            
                            // Initialize if not set
                            if (!isset($totalOutstanding[$currency])) {
                                $totalOutstanding[$currency] = 0;
                                $totalCustomersWithDebt[$currency] = 0;
                                $overLimitCustomers[$currency] = 0;
                            }
                            
                            // Add to totals if debt is positive
                            if ($debtAmount > 0) {
                                $totalOutstanding[$currency] += $debtAmount;
                                $totalCustomersWithDebt[$currency]++;
                                
                                // Check if over credit limit
                                if ($creditLimit > 0 && $debtAmount > $creditLimit) {
                                    $overLimitCustomers[$currency]++;
                                }
                            }
                        }
                        
                        // Display summary cards for each currency
                        foreach ($totalOutstanding as $curr => $amount) {
                            ?>
                            <div class="col-xl-4 col-md-6">
                                <div class="card card-animate">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center">
                                            <div class="flex-grow-1">
                                                <p class="text-uppercase fw-medium text-muted mb-0">Total Outstanding (<?php echo $curr; ?>)</p>
                                            </div>
                                            <div class="flex-shrink-0">
                                                <h5 class="text-success fs-14 mb-0">
                                                    <i class="ri-arrow-right-up-line fs-13 align-middle"></i> Active
                                                </h5>
                                            </div>
                                        </div>
                                        <div class="d-flex align-items-end justify-content-between mt-4">
                                            <div>
                                                <h4 class="fs-22 fw-semibold ff-secondary mb-2">
                                                    <span class="counter-value" data-target="<?php echo $amount; ?>"><?php echo $curr . ' ' . number_format($amount, 2); ?></span>
                                                </h4>
                                                <p class="text-muted mb-0">Outstanding Balance</p>
                                            </div>
                                            <div class="avatar-sm flex-shrink-0">
                                                <span class="avatar-title bg-light rounded fs-3">
                                                    <i class="ri-money-dollar-circle-line text-primary"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="mt-3">
                                            <div class="d-flex justify-content-between">
                                                <p class="text-muted mb-0">Clients with Debt: <?php echo $totalCustomersWithDebt[$curr]; ?></p>
                                                <p class="text-muted mb-0">Over Credit Limit: <?php echo $overLimitCustomers[$curr]; ?></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php
                        }
                        ?>
                    </div>
                </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'; ?>

    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        // Initialize DataTable
        $(document).ready(function() {
            $('#debt-table').DataTable({
                dom: 'Bfrtip',
                buttons: [
                    'csv', 'excel', 'pdf', 'print'
                ],
                lengthMenu: [
                    [10, 25, 50, -1],
                    [10, 25, 50, 'All']
                ],
                pageLength: 10,
                responsive: true
            });
            
            // Show success/error alerts using SweetAlert if needed
            <?php if (isset($_SESSION['swal_success'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: '<?php echo $_SESSION['swal_success']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_success']); ?>
            <?php endif; ?>
            
            <?php if (isset($_SESSION['swal_error'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: '<?php echo $_SESSION['swal_error']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_error']); ?>
            <?php endif; ?>
        });
        
        // Function to filter by currency
        function filterByCurrency(currency) {
            window.location.href = 'client_debt_management.php?currency=' + currency + '&search=<?php echo urlencode($search); ?>';
        }
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>