<?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', 'adjust_debt'], // Admin has all permissions
        '2' => ['view', 'edit', 'approve', 'invoice', 'adjust_debt'], // General Manager
        '3' => ['view', 'invoice'], // Operations
        '4' => ['view', 'invoice', 'adjust_debt'], // Finance
        '5' => ['view'], // 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 debt management
$canViewDebt = hasPermission($role_id, 'view');
$canManageDebt = hasPermission($role_id, 'adjust_debt');

if (!$canViewDebt) {
    $_SESSION['error_message'] = "You don't have permission to view client debt management.";
    header('Location: index.php');
    exit();
}

// Process credit limit update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_credit_limit']) && $canManageDebt) {
    $customerId = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;
    $currency = isset($_POST['currency']) ? trim($_POST['currency']) : '';
    $creditLimit = isset($_POST['credit_limit']) ? floatval($_POST['credit_limit']) : 0;
    
    // Basic validation
    $errors = [];
    
    if ($customerId <= 0) {
        $errors[] = "Please select a valid customer.";
    }
    
    if (empty($currency)) {
        $errors[] = "Currency is required.";
    }
    
    // If no errors, proceed with update
    if (empty($errors)) {
        $result = $debtController->updateCreditLimit($customerId, $currency, $creditLimit);
        
        if ($result) {
            $_SESSION['success_message'] = "Credit limit successfully updated.";
        } else {
            $_SESSION['error_message'] = "Failed to update credit limit. Please try again.";
        }
    } else {
        $_SESSION['error_message'] = implode('<br>', $errors);
    }
}

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

// Process currency filter
$currencyFilter = isset($_GET['currency']) ? $_GET['currency'] : '';
if (!empty($currencyFilter)) {
    $filteredDebts = [];
    foreach ($customerDebts as $debt) {
        if ($debt['currency'] == $currencyFilter) {
            $filteredDebts[] = $debt;
        }
    }
    $customerDebts = $filteredDebts;
}

// Get all unique currencies for filter dropdown
$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'];
    }
}

// If no currencies found, add default options
if (empty($currencies)) {
    $currencies = ['$', 'Tsh.', '€', '£'];
}

// 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";
}

// Include header files
include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Client Debt Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <style>
        .debt-card {
            transition: transform 0.3s;
        }
        .debt-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }
        .debt-amount {
            font-size: 1.25rem;
            font-weight: bold;
        }
        .debt-positive {
            color: #dc3545;
        }
        .debt-negative {
            color: #198754;
        }
        .credit-limit-progress {
            height: 8px;
            margin-top: 0.5rem;
        }
        .select2-container {
            width: 100% !important;
        }
    </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' => 'Financial Management', 'title' => 'Client Debt Management')); ?>

                    <!-- Success/Error Messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <!-- Summary Cards -->
                    <div class="row">
                        <?php
                        // Calculate totals by currency
                        $totals = [];
                        $customerCount = 0;
                        $overdueCount = 0;
                        
                        foreach ($customerDebts as $debt) {
                            if (!isset($totals[$debt['currency']])) {
                                $totals[$debt['currency']] = 0;
                            }
                            $totals[$debt['currency']] += $debt['total_debt'];
                            
                            // Count unique customers
                            $customerCount = count(array_unique(array_column($customerDebts, 'customer_id')));
                            
                            // Count overdue (over credit limit)
                            if (isset($debt['credit_limit']) && $debt['credit_limit'] > 0 && $debt['total_debt'] > $debt['credit_limit']) {
                                $overdueCount++;
                            }
                        }
                        ?>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-light text-primary rounded-circle fs-3">
                                                <i class="ri-user-3-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-medium text-muted mb-1">Total Customers</p>
                                            <h4 class="mb-0"><?php echo $customerCount; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-light text-warning rounded-circle fs-3">
                                                <i class="ri-alert-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-medium text-muted mb-1">Over Credit Limit</p>
                                            <h4 class="mb-0"><?php echo $overdueCount; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <?php foreach ($totals as $currency => $total): ?>
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-light text-<?php echo $total > 0 ? 'danger' : 'success'; ?> rounded-circle fs-3">
                                                <i class="ri-money-<?php echo $currency == '$' ? 'dollar' : 'euro'; ?>-circle-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-medium text-muted mb-1">Total Debt (<?php echo $currency; ?>)</p>
                                            <h4 class="mb-0 <?php echo $total > 0 ? 'text-danger' : 'text-success'; ?>">
                                                <?php echo $currency . ' ' . number_format(abs($total), 2); ?>
                                            </h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Actions and Filters -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="d-flex">
                                <?php if ($canManageDebt): ?>
                                <a href="debt_adjustment.php" class="btn btn-primary me-2">
                                    <i class="ri-add-line me-1"></i> New Adjustment
                                </a>
                                <?php endif; ?>
                                <a href="debt_statement.php" class="btn btn-success me-2">
                                    <i class="ri-file-list-3-line me-1"></i> Generate Statement
                                </a>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <form method="GET" class="d-flex justify-content-end">
                                <div class="input-group" style="max-width: 300px;">
                                    <select class="form-select" name="currency" onchange="this.form.submit()">
                                        <option value="">All Currencies</option>
                                        <?php foreach ($currencies as $curr): ?>
                                        <option value="<?php echo $curr; ?>" <?php echo ($currencyFilter == $curr) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($curr); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <button class="btn btn-outline-secondary" type="submit">
                                        <i class="ri-filter-line"></i>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Client Debt Table -->
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Client Debt Overview</h4>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($customerDebts)): ?>
                                    <div class="text-center py-4">
                                        <div class="avatar-md mx-auto mb-3">
                                            <div class="avatar-title bg-light text-primary rounded-circle">
                                                <i class="ri-money-dollar-circle-line fs-24"></i>
                                            </div>
                                        </div>
                                        <h5 class="mb-1">No debt records found</h5>
                                        <p class="text-muted">
                                            <?php if (!empty($currencyFilter)): ?>
                                            No debt records found for currency: <?php echo htmlspecialchars($currencyFilter); ?>
                                            <?php else: ?>
                                            There are no client debt records in the system yet.
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                    <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover table-centered align-middle">
                                            <thead>
                                                <tr>
                                                    <th>Customer</th>
                                                    <th>Contact</th>
                                                    <th>Currency</th>
                                                    <th>Total Debt</th>
                                                    <th>Credit Limit</th>
                                                    <th>Status</th>
                                                    <th>Last Updated</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($customerDebts as $debt): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="flex-shrink-0 me-2">
                                                                <div class="avatar-xs">
                                                                    <div class="avatar-title bg-soft-primary text-primary rounded">
                                                                        <?php 
                                                                        $initials = '';
                                                                        if (!empty($debt['first_name'])) $initials .= substr($debt['first_name'], 0, 1);
                                                                        if (!empty($debt['last_name'])) $initials .= substr($debt['last_name'], 0, 1);
                                                                        echo strtoupper($initials);
                                                                        ?>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div>
                                                                <h5 class="mb-0 fs-13">
                                                                    <?php echo htmlspecialchars($debt['first_name'] . ' ' . $debt['last_name']); ?>
                                                                </h5>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php if (!empty($debt['phone_number'])): ?>
                                                        <div class="d-flex align-items-center">
                                                            <i class="ri-phone-line me-1"></i>
                                                            <?php echo htmlspecialchars($debt['phone_number']); ?>
                                                        </div>
                                                        <?php endif; ?>
                                                        <?php if (!empty($debt['email'])): ?>
                                                        <div class="d-flex align-items-center">
                                                            <i class="ri-mail-line me-1"></i>
                                                            <?php echo htmlspecialchars($debt['email']); ?>
                                                        </div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($debt['currency']); ?></td>
                                                    <td>
                                                        <span class="debt-amount <?php echo $debt['total_debt'] > 0 ? 'debt-positive' : ($debt['total_debt'] < 0 ? 'debt-negative' : ''); ?>">
                                                            <?php echo htmlspecialchars($debt['currency'] . ' ' . number_format($debt['total_debt'], 2)); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php if (!is_null($debt['credit_limit']) && $debt['credit_limit'] > 0): ?>
                                                        <div>
                                                            <?php echo htmlspecialchars($debt['currency'] . ' ' . number_format($debt['credit_limit'], 2)); ?>
                                                            
                                                            <?php 
                                                            $percentUsed = ($debt['total_debt'] / $debt['credit_limit']) * 100;
                                                            $percentUsed = max(0, min(100, $percentUsed)); // Clamp between 0-100
                                                            $progressClass = $percentUsed < 70 ? 'bg-success' : ($percentUsed < 90 ? 'bg-warning' : 'bg-danger');
                                                            ?>
                                                            <div class="progress credit-limit-progress">
                                                                <div class="progress-bar <?php echo $progressClass; ?>" role="progressbar" style="width: <?php echo $percentUsed; ?>%" aria-valuenow="<?php echo $percentUsed; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                                            </div>
                                                        </div>
                                                        <?php else: ?>
                                                        <span class="text-muted">Not set</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        $statusClass = '';
                                                        $statusText = 'Normal';
                                                        
                                                        if (!is_null($debt['credit_limit']) && $debt['credit_limit'] > 0) {
                                                            $percentUsed = ($debt['total_debt'] / $debt['credit_limit']) * 100;
                                                            
                                                            if ($percentUsed >= 100) {
                                                                $statusClass = 'bg-danger';
                                                                $statusText = 'Over Limit';
                                                            } else if ($percentUsed >= 90) {
                                                                $statusClass = 'bg-warning';
                                                                $statusText = 'Near Limit';
                                                            } else if ($percentUsed >= 70) {
                                                                $statusClass = 'bg-info';
                                                                $statusText = 'Approaching';
                                                            } else {
                                                                $statusClass = 'bg-success';
                                                                $statusText = 'Normal';
                                                            }
                                                        } else if ($debt['total_debt'] > 1000) {
                                                            // If no credit limit but debt is high
                                                            $statusClass = 'bg-warning';
                                                            $statusText = 'High Debt';
                                                        } else if ($debt['total_debt'] < 0) {
                                                            // If customer has credit (negative debt)
                                                            $statusClass = 'bg-info';
                                                            $statusText = 'Credit';
                                                        }
                                                        ?>
                                                        <span class="badge <?php echo $statusClass; ?>"><?php echo $statusText; ?></span>
                                                    </td>
                                                    <td>
                                                        <?php echo date('M d, Y', strtotime($debt['last_updated'])); ?>
                                                    </td>
                                                    <td>
                                                        <div class="d-flex gap-2">
                                                            <a href="debt_statement.php?customer_id=<?php echo $debt['customer_id']; ?>&currency=<?php echo $debt['currency']; ?>" class="btn btn-sm btn-soft-primary">
                                                                <i class="ri-file-list-3-line"></i>
                                                            </a>
                                                            <?php if ($canManageDebt): ?>
                                                            <a href="debt_adjustment.php?customer_id=<?php echo $debt['customer_id']; ?>" class="btn btn-sm btn-soft-success">
                                                                <i class="ri-exchange-dollar-line"></i>
                                                            </a>
                                                            <button type="button" class="btn btn-sm btn-soft-warning edit-credit-limit" 
                                                                    data-bs-toggle="modal" 
                                                                    data-bs-target="#editCreditLimitModal"
                                                                    data-customer-id="<?php echo $debt['customer_id']; ?>"
                                                    data-customer-name="<?php echo htmlspecialchars($debt['first_name'] . ' ' . $debt['last_name']); ?>"
                                                    data-currency="<?php echo $debt['currency']; ?>"
                                                    data-credit-limit="<?php echo $debt['credit_limit']; ?>">
                                                <i class="ri-edit-line"></i>
                                            </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
<!-- container-fluid -->
</div>
<!-- End Page-content -->

<!-- Credit Limit Modal -->
<?php if ($canManageDebt): ?>
<div class="modal fade" id="editCreditLimitModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-light p-3">
                <h5 class="modal-title" id="creditLimitModalTitle">Update Credit Limit</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="" method="POST">
                <div class="modal-body">
                    <input type="hidden" name="update_credit_limit" value="1">
                    <input type="hidden" id="modal_customer_id" name="customer_id" value="">
                    <input type="hidden" id="modal_currency" name="currency" value="">
                    
                    <div class="mb-3">
                        <label class="form-label">Customer</label>
                        <input type="text" class="form-control" id="modal_customer_name" readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Currency</label>
                        <input type="text" class="form-control" id="modal_currency_display" readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label for="credit_limit" class="form-label">Credit Limit</label>
                        <input type="number" class="form-control" id="credit_limit" name="credit_limit" min="0" step="0.01" required>
                        <div class="form-text">Set to 0 for no limit.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<?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>
<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>
document.addEventListener('DOMContentLoaded', function() {
    // Handle edit credit limit button click
    const editButtons = document.querySelectorAll('.edit-credit-limit');
    editButtons.forEach(button => {
        button.addEventListener('click', function() {
            const customerId = this.getAttribute('data-customer-id');
            const customerName = this.getAttribute('data-customer-name');
            const currency = this.getAttribute('data-currency');
            const creditLimit = this.getAttribute('data-credit-limit');
            
            // Set modal values
            document.getElementById('modal_customer_id').value = customerId;
            document.getElementById('modal_customer_name').value = customerName;
            document.getElementById('modal_currency').value = currency;
            document.getElementById('modal_currency_display').value = currency;
            document.getElementById('credit_limit').value = creditLimit || 0;
        });
    });
});
</script>

</body>
</html>