<?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();
}

// Check if customer ID and currency are provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "Customer ID is required";
    header('Location: client_debt_management.php');
    exit();
}

$customerId = intval($_GET['id']);
$currency = $_GET['currency'] ?? null;

// 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
$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();
}

// Get customer debt details
$customerDebt = $debtController->getCustomerDebt($customerId, $currency);

if (empty($customerDebt)) {
    $_SESSION['error_message'] = "Customer not found or no debt records available";
    header('Location: client_debt_management.php');
    exit();
}

// Get customer information
$sql_customer = "SELECT * FROM customers WHERE customer_id = ?";
$stmt_customer = $conn->prepare($sql_customer);
$stmt_customer->bind_param('i', $customerId);
$stmt_customer->execute();
$result_customer = $stmt_customer->get_result();
$customer = $result_customer->fetch_assoc();

// Handle filtering for transactions
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : null;
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : null;
$transactionType = isset($_GET['transaction_type']) ? $_GET['transaction_type'] : null;

// Get debt transactions
$transactions = $debtController->getDebtTransactions($customerId, $currency, $startDate, $endDate);

// Filter by transaction type if specified
if ($transactionType) {
    $filteredTransactions = [];
    foreach ($transactions as $transaction) {
        if ($transaction['transaction_type'] == $transactionType) {
            $filteredTransactions[] = $transaction;
        }
    }
    $transactions = $filteredTransactions;
}

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

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Client Debt Details')); ?>
    <?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" />
    
    <!-- Datepicker css -->
    <link rel="stylesheet" href="assets/libs/flatpickr/flatpickr.min.css">
    
    <style>
        .client-info-card {
            margin-bottom: 20px;
        }
        .transaction-badge {
            padding: 5px 8px;
        }
        .transaction-badge.positive {
            background-color: #f46a6a;
            color: white;
        }
        .transaction-badge.negative {
            background-color: #34c38f;
            color: white;
        }
        .transaction-badge.zero {
            background-color: #74788d;
            color: white;
        }
        .filters-container {
            margin-bottom: 20px;
        }
        .running-balance {
            font-weight: bold;
        }
        .credit-limit-status {
            padding: 0.5rem;
            border-radius: 0.25rem;
            font-weight: bold;
            text-align: center;
            margin-top: 1rem;
        }
        .credit-limit-status.ok {
            background-color: #d1e7dd;
            color: #0f5132;
        }
        .credit-limit-status.warning {
            background-color: #fff3cd;
            color: #664d03;
        }
        .credit-limit-status.danger {
            background-color: #f8d7da;
            color: #842029;
        }
        .credit-limit-status.no-limit {
            background-color: #e2e3e5;
            color: #41464b;
        }
    </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 Details')); ?>

                    <?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">
                        <!-- Client Information Card -->
                        <div class="col-xl-4">
                            <div class="card client-info-card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Client Information</h4>
                                </div>
                                <div class="card-body">
                                    <div class="text-center mb-4">
                                        <div class="profile-user position-relative d-inline-block mx-auto">
                                            <img src="assets/images/users/avatar-1.jpg" class="rounded-circle avatar-xl img-thumbnail user-profile-image" alt="User Profile Picture">
                                        </div>
                                        <h5 class="fs-16 mb-1"><?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?></h5>
                                        <p class="text-muted mb-0">Customer ID: <?php echo $customerId; ?></p>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <th><i class="ri-phone-line me-2"></i> Phone:</th>
                                                    <td><?php echo htmlspecialchars($customer['phone_number'] ?? 'N/A'); ?></td>
                                                </tr>
                                                <tr>
                                                    <th><i class="ri-mail-line me-2"></i> Email:</th>
                                                    <td><?php echo htmlspecialchars($customer['email'] ?? 'N/A'); ?></td>
                                                </tr>
                                                <tr>
                                                    <th><i class="ri-map-pin-line me-2"></i> Address:</th>
                                                    <td><?php echo htmlspecialchars($customer['address'] ?? 'N/A'); ?></td>
                                                </tr>
                                                <tr>
                                                    <th><i class="ri-building-line me-2"></i> City/Country:</th>
                                                    <td>
                                                        <?php 
                                                        $location = [];
                                                        if (!empty($customer['city'])) $location[] = $customer['city'];
                                                        if (!empty($customer['country'])) $location[] = $customer['country'];
                                                        echo htmlspecialchars(implode(', ', $location) ?: 'N/A');
                                                        ?>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Debt Summary Card -->
                            <?php foreach ($customerDebt as $debt): ?>
                            <div class="card client-info-card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Debt Summary (<?php echo $debt['currency']; ?>)</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <th>Current Balance:</th>
                                                    <td>
                                                        <?php 
                                                        $totalDebt = $debt['total_debt'] ?? 0;
                                                        $debtClass = 'zero';
                                                        if ($totalDebt > 0) $debtClass = 'positive';
                                                        if ($totalDebt < 0) $debtClass = 'negative';
                                                        ?>
                                                        <span class="badge transaction-badge <?php echo $debtClass; ?>">
                                                            <?php echo $debt['currency'] . ' ' . number_format($totalDebt, 2); ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <th>Credit Limit:</th>
                                                    <td>
                                                        <?php 
                                                        if (isset($debt['credit_limit']) && $debt['credit_limit'] > 0) {
                                                            echo $debt['currency'] . ' ' . number_format($debt['credit_limit'], 2);
                                                        } else {
                                                            echo '<span class="text-muted">Not set</span>';
                                                        }
                                                        ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <th>Last Updated:</th>
                                                    <td>
                                                        <?php 
                                                        echo !empty($debt['last_updated']) ? 
                                                            date('Y-m-d H:i', strtotime($debt['last_updated'])) : 
                                                            'N/A';
                                                        ?>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <?php
                                    // Show credit limit status 
                                    $creditLimitStatus = '';
                                    $creditLimitClass = '';
                                    
                                    if (isset($debt['credit_limit']) && $debt['credit_limit'] > 0) {
                                        $usedPercentage = ($totalDebt / $debt['credit_limit']) * 100;
                                        
                                        if ($totalDebt <= 0) {
                                            $creditLimitStatus = 'No outstanding debt';
                                            $creditLimitClass = 'ok';
                                        } elseif ($usedPercentage < 80) {
                                            $creditLimitStatus = 'Within limit (' . number_format($usedPercentage, 1) . '%)';
                                            $creditLimitClass = 'ok';
                                        } elseif ($usedPercentage < 100) {
                                            $creditLimitStatus = 'Approaching limit (' . number_format($usedPercentage, 1) . '%)';
                                            $creditLimitClass = 'warning';
                                        } else {
                                            $creditLimitStatus = 'Over limit (' . number_format($usedPercentage, 1) . '%)';
                                            $creditLimitClass = 'danger';
                                        }
                                    } else {
                                        $creditLimitStatus = 'No credit limit set';
                                        $creditLimitClass = 'no-limit';
                                    }
                                    ?>
                                    
                                    <div class="credit-limit-status <?php echo $creditLimitClass; ?>">
                                        <?php echo $creditLimitStatus; ?>
                                    </div>
                                </div>
                                
                                <?php if ($can_edit): ?>
                                <div class="card-footer">
                                    <div class="d-flex justify-content-center gap-1">
                                        <a href="debt_adjustment.php?customer_id=<?php echo $customerId; ?>&currency=<?php echo $debt['currency']; ?>" class="btn btn-primary btn-sm">
                                            <i class="ri-add-line align-bottom"></i> Add Adjustment
                                        </a>
                                        <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#creditLimitModal" data-currency="<?php echo $debt['currency']; ?>" data-limit="<?php echo $debt['credit_limit'] ?? 0; ?>">
                                            <i class="ri-edit-line align-bottom"></i> Set Credit Limit
                                        </button>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                            
                            <!-- Quick Actions Card -->
                            <div class="card client-info-card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Quick Actions</h4>
                                </div>
                                <div class="card-body">
                                    <div class="d-grid gap-2">
                                        <a href="client_debt_management.php" class="btn btn-soft-primary">
                                            <i class="ri-arrow-left-line align-bottom"></i> Back to Client List
                                        </a>
                                        <?php if ($can_edit): ?>
                                        <a href="create_credit_note.php?customer_id=<?php echo $customerId; ?>&currency=<?php echo $currency; ?>" class="btn btn-soft-success">
                                            <i class="ri-file-reduce-line align-bottom"></i> Create Credit Note
                                        </a>
                                        <a href="create_debit_note.php?customer_id=<?php echo $customerId; ?>&currency=<?php echo $currency; ?>" class="btn btn-soft-warning">
                                            <i class="ri-file-add-line align-bottom"></i> Create Debit Note
                                        </a>
                                        <?php endif; ?>
                                        <a href="view_customer.php?id=<?php echo $customerId; ?>" class="btn btn-soft-info">
                                            <i class="ri-user-line align-bottom"></i> View Customer Profile
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Transaction History -->
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0 flex-grow-1">Transaction History</h4>
                                </div>
                                <div class="card-body">
                                    <!-- Filters -->
                                    <div class="filters-container">
                                        <form action="" method="GET" class="row g-3">
                                            <input type="hidden" name="id" value="<?php echo $customerId; ?>">
                                            <input type="hidden" name="currency" value="<?php echo $currency; ?>">
                                            
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Start Date</label>
                                                    <input type="text" class="form-control flatpickr-input" id="start-date" name="start_date" placeholder="Select start date" value="<?php echo $startDate ?? ''; ?>">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">End Date</label>
                                                    <input type="text" class="form-control flatpickr-input" id="end-date" name="end_date" placeholder="Select end date" value="<?php echo $endDate ?? ''; ?>">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Transaction Type</label>
                                                    <select class="form-select" name="transaction_type">
                                                        <option value="">All Types</option>
                                                        <option value="invoice" <?php echo $transactionType == 'invoice' ? 'selected' : ''; ?>>Invoice</option>
                                                        <option value="payment" <?php echo $transactionType == 'payment' ? 'selected' : ''; ?>>Payment</option>
                                                        <option value="credit_note" <?php echo $transactionType == 'credit_note' ? 'selected' : ''; ?>>Credit Note</option>
                                                        <option value="debit_note" <?php echo $transactionType == 'debit_note' ? 'selected' : ''; ?>>Debit Note</option>
                                                        <option value="adjustment" <?php echo $transactionType == 'adjustment' ? 'selected' : ''; ?>>Adjustment</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3 d-flex align-items-end">
                                                <div class="form-group w-100">
                                                    <button type="submit" class="btn btn-primary w-100">Apply Filters</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                    
                                    <!-- Transactions Table -->
                                    <div class="table-responsive">
                                        <table id="transactions-table" class="table table-bordered dt-responsive nowrap table-striped align-middle">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Transaction Type</th>
                                                    <th>Reference</th>
                                                    <th>Amount</th>
                                                    <th>Running Balance</th>
                                                    <th>Notes</th>
                                                    <th>Created By</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                if (!empty($transactions)) {
                                                    $runningBalance = 0;
                                                    
                                                    // Reverse transactions to show oldest first for running balance calculation
                                                    $sortedTransactions = $transactions;
                                                    usort($sortedTransactions, function($a, $b) {
                                                        return strtotime($a['transaction_date']) - strtotime($b['transaction_date']);
                                                    });
                                                    
                                                    foreach ($sortedTransactions as $transaction) {
                                                        $runningBalance += $transaction['amount'];
                                                        
                                                        // Determine transaction type display
                                                        $transactionTypeDisplay = ucfirst(str_replace('_', ' ', $transaction['transaction_type']));
                                                        
                                                        // Determine amount class
                                                        $amountClass = 'zero';
                                                        if ($transaction['amount'] > 0) $amountClass = 'positive';
                                                        if ($transaction['amount'] < 0) $amountClass = 'negative';
                                                        
                                                        // Determine balance class
                                                        $balanceClass = 'zero';
                                                        if ($runningBalance > 0) $balanceClass = 'positive';
                                                        if ($runningBalance < 0) $balanceClass = 'negative';
                                                        
                                                        echo "<tr>";
                                                        echo "<td>" . date('Y-m-d', strtotime($transaction['transaction_date'])) . "</td>";
                                                        echo "<td>{$transactionTypeDisplay}</td>";
                                                        
                                                        // Reference with link based on type
                                                        $referenceCell = $transaction['reference_id'] ?? 'N/A';
                                                        if (!empty($transaction['reference_id'])) {
                                                            switch ($transaction['transaction_type']) {
                                                                case 'invoice':
                                                                    // Extract invoice ID from reference
                                                                    $invoiceNumber = $transaction['reference_id'];
                                                                    $sql = "SELECT invoice_id FROM invoices WHERE invoice_number = ?";
                                                                    $stmt = $conn->prepare($sql);
                                                                    $stmt->bind_param('s', $invoiceNumber);
                                                                    $stmt->execute();
                                                                    $result = $stmt->get_result();
                                                                    if ($result->num_rows > 0) {
                                                                        $invoiceRow = $result->fetch_assoc();
                                                                        $referenceCell = "<a href='view_invoice.php?id={$invoiceRow['invoice_id']}' class='link-primary'>{$invoiceNumber}</a>";
                                                                    }
                                                                    break;
                                                                case 'credit_note':
                                                                    // Extract note ID from reference
                                                                    $noteNumber = $transaction['reference_id'];
                                                                    $sql = "SELECT note_id FROM notes WHERE note_number = ? AND note_type = 'credit'";
                                                                    $stmt = $conn->prepare($sql);
                                                                    $stmt->bind_param('s', $noteNumber);
                                                                    $stmt->execute();
                                                                    $result = $stmt->get_result();
                                                                    if ($result->num_rows > 0) {
                                                                        $noteRow = $result->fetch_assoc();
                                                                        $referenceCell = "<a href='view_note.php?id={$noteRow['note_id']}' class='link-success'>{$noteNumber}</a>";
                                                                    }
                                                                    break;
                                                                case 'debit_note':
                                                                    // Extract note ID from reference
                                                                    $noteNumber = $transaction['reference_id'];
                                                                    $sql = "SELECT note_id FROM notes WHERE note_number = ? AND note_type = 'debit'";
                                                                    $stmt = $conn->prepare($sql);
                                                                    $stmt->bind_param('s', $noteNumber);
                                                                    $stmt->execute();
                                                                    $result = $stmt->get_result();
                                                                    if ($result->num_rows > 0) {
                                                                        $noteRow = $result->fetch_assoc();
                                                                        $referenceCell = "<a href='view_note.php?id={$noteRow['note_id']}' class='link-warning'>{$noteNumber}</a>";
                                                                    }
                                                                    break;
                                                                default:
                                                                    $referenceCell = htmlspecialchars($transaction['reference_id']);
                                                            }
                                                        }
                                                        echo "<td>{$referenceCell}</td>";
                                                        
                                                        echo "<td><span class='badge transaction-badge {$amountClass}'>" . $transaction['currency'] . " " . number_format($transaction['amount'], 2) . "</span></td>";
                                                        echo "<td><span class='badge transaction-badge {$balanceClass} running-balance'>" . $transaction['currency'] . " " . number_format($runningBalance, 2) . "</span></td>";
                                                        echo "<td>" . htmlspecialchars($transaction['notes'] ?? '') . "</td>";
                                                        echo "<td>" . htmlspecialchars($transaction['created_by'] ?? 'System') . "</td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='7' class='text-center'>No transactions found</td></tr>";
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

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

    <!-- Credit Limit Modal -->
    <?php if ($can_edit): ?>
    <div class="modal fade" id="creditLimitModal" tabindex="-1" aria-labelledby="creditLimitModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="creditLimitModalLabel">Set Credit Limit</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="update_credit_limit.php" method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="customer_id" value="<?php echo $customerId; ?>">
                        <input type="hidden" name="currency" id="modal-currency">
                        
                        <div class="mb-3">
                            <label for="credit-limit" class="form-label">Credit Limit</label>
                            <div class="input-group">
                                <span class="input-group-text" id="currency-addon"></span>
                                <input type="number" class="form-control" id="credit-limit" name="credit_limit" step="0.01" min="0" required>
                            </div>
                            <div class="form-text">Set to 0 to remove credit 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/vendor-scripts.php'; ?>

    <!-- DataTables JS -->
    <script src="assets/libs/datatables/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables/dataTables.bootstrap5.min.js"></script>
    <script src="assets/libs/datatables/dataTables.buttons.min.js"></script>
    <script src="assets/libs/datatables/buttons.bootstrap5.min.js"></script>
    <script src="assets/libs/datatables/buttons.html5.min.js"></script>
    <script src="assets/libs/datatables/buttons.print.min.js"></script>
    <script src="assets/libs/datatables/dataTables.responsive.min.js"></script>
    <script src="assets/libs/datatables/responsive.bootstrap5.min.js"></script>
    
    <!-- Sweet Alerts js -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <!-- Datepicker js -->
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
</body>
</html>