<?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 adjust debt
$canAdjustDebt = hasPermission($role_id, 'adjust_debt');

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

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_adjustment'])) {
    // Validate input
    $customerId = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;
    $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
    $currency = isset($_POST['currency']) ? trim($_POST['currency']) : '';
    $transactionDate = isset($_POST['transaction_date']) ? trim($_POST['transaction_date']) : date('Y-m-d');
    $referenceId = isset($_POST['reference_id']) ? trim($_POST['reference_id']) : null;
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
    
    // Basic validation
    $errors = [];
    
    if ($customerId <= 0) {
        $errors[] = "Please select a valid customer.";
    }
    
    if ($amount == 0) {
        $errors[] = "Amount cannot be zero.";
    }
    
    if (empty($currency)) {
        $errors[] = "Currency is required.";
    }
    
    if (empty($transactionDate)) {
        $errors[] = "Transaction date is required.";
    }
    
    if (empty($notes)) {
        $errors[] = "Please provide a reason for this adjustment.";
    }
    
    // If no errors, proceed with adjustment
    if (empty($errors)) {
        // Create adjustment data
        $adjustmentData = [
            'customer_id' => $customerId,
            'transaction_date' => $transactionDate,
            'amount' => $amount,
            'currency' => $currency,
            'reference_id' => $referenceId,
            'notes' => $notes,
            'user_id' => $user_id
        ];
        
        // Add debt adjustment
        $result = $debtController->addDebtAdjustment($adjustmentData);
        
        if ($result) {
            $_SESSION['success_message'] = "Debt adjustment successfully applied.";
            header('Location: debt_adjustment.php?customer_id=' . $customerId);
            exit();
        } else {
            $_SESSION['error_message'] = "Failed to apply debt adjustment. Please try again.";
        }
    } else {
        $_SESSION['error_message'] = implode('<br>', $errors);
    }
}

// Get customer list for dropdown
$sql_customers = "SELECT customer_id, first_name, last_name FROM customers ORDER BY first_name, last_name";
$result_customers = $conn->query($sql_customers);
$customers = [];

if ($result_customers && $result_customers->num_rows > 0) {
    while ($row = $result_customers->fetch_assoc()) {
        $customers[] = $row;
    }
}

// Get customer debt details if customer_id is provided
$selectedCustomerId = isset($_GET['customer_id']) ? intval($_GET['customer_id']) : 0;
$customerDebts = [];
$transactions = [];
$customerDetails = null;

if ($selectedCustomerId > 0) {
    // Get customer details
    $customerDetails = $debtController->getCustomerDetails($selectedCustomerId);
    
    // Get all debts for this customer
    $customerDebts = $debtController->getCustomerDebt($selectedCustomerId);
    
    // Get the most recent transactions (limit to 20)
    $transactions = $debtController->getDebtTransactions($selectedCustomerId, null, null, null, 20);
}

// 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 Adjustment')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <style>
        .client-details-card {
            margin-bottom: 1.5rem;
        }
        .debt-amount {
            font-size: 1.5rem;
            font-weight: bold;
        }
        .debt-positive {
            color: #dc3545;
        }
        .debt-negative {
            color: #198754;
        }
        .transaction-item {
            padding: 0.75rem;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }
        .transaction-item:hover {
            background-color: #f8f9fa;
        }
        .transaction-amount-positive {
            color: #dc3545;
        }
        .transaction-amount-negative {
            color: #198754;
        }
        .transaction-date {
            color: #6c757d;
            font-size: 0.875rem;
        }
        .transaction-type {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            text-transform: uppercase;
        }
        .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 Adjustment')); ?>

                    <!-- 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; ?>

                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Select Customer</h4>
                                </div>
                                <div class="card-body">
                                    <form method="GET" action="">
                                        <div class="row mb-3">
                                            <div class="col-md-8">
                                                <label for="customer_select" class="form-label">Customer</label>
                                                <select class="form-select select2" id="customer_select" name="customer_id">
                                                    <option value="">Select a customer</option>
                                                    <?php foreach ($customers as $customer): ?>
                                                    <option value="<?php echo $customer['customer_id']; ?>" <?php echo ($selectedCustomerId == $customer['customer_id']) ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?>
                                                    </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4 d-flex align-items-end">
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="ri-search-line me-1"></i> View Customer
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if ($selectedCustomerId > 0 && $customerDetails): ?>
                    <div class="row">
                        <div class="col-xl-4">
                            <!-- Customer Details -->
                            <div class="card client-details-card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Customer Details</h4>
                                </div>
                                <div class="card-body">
                                    <div class="text-center mb-4">
                                        <div class="avatar-lg mx-auto mb-4">
                                            <div class="avatar-title bg-light text-primary display-4 rounded-circle">
                                                <i class="ri-user-line"></i>
                                            </div>
                                        </div>
                                        <h5 class="mb-0"><?php echo htmlspecialchars($customerDetails['first_name'] . ' ' . $customerDetails['last_name']); ?></h5>
                                        <p class="text-muted"><?php echo htmlspecialchars($customerDetails['email'] ?? 'No email available'); ?></p>
                                    </div>

                                    <div class="d-flex align-items-center mb-3">
                                        <i class="ri-phone-line me-2 text-muted"></i>
                                        <div>
                                            <p class="mb-0 text-muted">Phone</p>
                                            <h6 class="mb-0"><?php echo htmlspecialchars($customerDetails['phone_number'] ?? 'N/A'); ?></h6>
                                        </div>
                                    </div>

                                    <div class="d-flex align-items-center mb-3">
                                        <i class="ri-map-pin-line me-2 text-muted"></i>
                                        <div>
                                            <p class="mb-0 text-muted">Location</p>
                                            <h6 class="mb-0"><?php echo htmlspecialchars(($customerDetails['city'] ?? '') . ', ' . ($customerDetails['country'] ?? 'N/A')); ?></h6>
                                        </div>
                                    </div>

                                    <hr class="my-4">

                                    <h5 class="mb-3">Debt Summary</h5>
                                    <?php if (empty($customerDebts)): ?>
                                        <p class="text-muted">No debt records found for this customer.</p>
                                    <?php else: ?>
                                        <?php foreach ($customerDebts as $debt): ?>
                                            <div class="d-flex justify-content-between align-items-center mb-3">
                                                <div>
                                                    <h6 class="mb-0"><?php echo htmlspecialchars($debt['currency']); ?> Balance</h6>
                                                    <small class="text-muted">Last updated: <?php echo date('M d, Y', strtotime($debt['last_updated'])); ?></small>
                                                </div>
                                                <div>
                                                    <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>
                                                </div>
                                            </div>
                                            <?php if (!is_null($debt['credit_limit']) && $debt['credit_limit'] > 0): ?>
                                                <div class="progress mb-3" style="height: 10px;">
                                                    <?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-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 class="d-flex justify-content-between">
                                                    <small class="text-muted">Credit Limit</small>
                                                    <small><?php echo htmlspecialchars($debt['currency'] . ' ' . number_format($debt['credit_limit'], 2)); ?></small>
                                                </div>
                                            <?php endif; ?>
                                            <hr class="my-3">
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <!-- End Customer Details -->
                        </div>

                        <div class="col-xl-8">
                            <!-- Debt Adjustment Form -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Add Debt Adjustment</h4>
                                </div>
                                <div class="card-body">
                                    <form action="" method="POST" id="debt-adjustment-form">
                                        <input type="hidden" name="customer_id" value="<?php echo $selectedCustomerId; ?>">
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Adjustment Amount</label>
                                                <div class="input-group">
                                                    <span class="input-group-text">Amount</span>
                                                    <input type="number" class="form-control" name="amount" step="0.01" required>
                                                    <span class="form-group-text text-muted">
                                                        <small>Positive for debit, negative for credit</small>
                                                    </span>
                                                </div>
                                                <small class="text-muted">Enter a positive amount to increase debt, negative to decrease debt.</small>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Currency</label>
                                                <select class="form-select" name="currency" required>
                                                    <option value="">Select Currency</option>
                                                    <option value="$">USD ($)</option>
                                                    <option value="Tsh.">TZS (Tsh.)</option>
                                                    <option value="€">EUR (€)</option>
                                                    <option value="£">GBP (£)</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Transaction Date</label>
                                                <input type="text" class="form-control flatpickr-date" name="transaction_date" value="<?php echo date('Y-m-d'); ?>" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Reference ID (Optional)</label>
                                                <input type="text" class="form-control" name="reference_id" placeholder="e.g., Receipt #, Credit Note #">
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Reason / Notes</label>
                                            <textarea class="form-control" name="notes" rows="3" required placeholder="Provide a detailed reason for this adjustment"></textarea>
                                        </div>

                                        <div class="text-end">
                                            <button type="submit" name="submit_adjustment" class="btn btn-primary">
                                                <i class="ri-save-line me-1"></i> Save Adjustment
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            <!-- End Debt Adjustment Form -->
                            
                            <!-- Recent Transactions -->
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h4 class="card-title mb-0">Recent Transactions</h4>
                                    <a href="debt_statement.php?customer_id=<?php echo $selectedCustomerId; ?>" class="btn btn-sm btn-success">
                                        <i class="ri-file-list-3-line me-1"></i> Full Statement
                                    </a>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($transactions)): ?>
                                        <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-exchange-funds-line fs-24"></i>
                                                </div>
                                            </div>
                                            <h5 class="mb-1">No transactions found</h5>
                                            <p class="text-muted">This customer doesn't have any debt transactions yet.</p>
                                        </div>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-hover table-centered mb-0">
                                                <thead>
                                                    <tr>
                                                        <th>Date</th>
                                                        <th>Type</th>
                                                        <th>Reference</th>
                                                        <th>Amount</th>
                                                        <th>Notes</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($transactions as $transaction): ?>
                                                        <tr>
                                                            <td>
                                                                <div class="d-flex flex-column">
                                                                    <span><?php echo date('M d, Y', strtotime($transaction['transaction_date'])); ?></span>
                                                                    <small class="text-muted"><?php echo date('h:i A', strtotime($transaction['created_at'])); ?></small>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <?php 
                                                                // Set badge color based on transaction type
                                                                $typeClass = '';
                                                                switch ($transaction['transaction_type']) {
                                                                    case 'invoice':
                                                                        $typeClass = 'bg-primary';
                                                                        break;
                                                                    case 'payment':
                                                                        $typeClass = 'bg-success';
                                                                        break;
                                                                    case 'credit_note':
                                                                        $typeClass = 'bg-info';
                                                                        break;
                                                                    case 'debit_note':
                                                                        $typeClass = 'bg-warning';
                                                                        break;
                                                                    case 'adjustment':
                                                                        $typeClass = 'bg-secondary';
                                                                        break;
                                                                    default:
                                                                        $typeClass = 'bg-dark';
                                                                }
                                                                ?>
                                                                <span class="badge <?php echo $typeClass; ?>"><?php echo ucfirst(str_replace('_', ' ', $transaction['transaction_type'])); ?></span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($transaction['reference_id'] ?: 'N/A'); ?></td>
                                                            <td>
                                                                <span class="<?php echo $transaction['amount'] > 0 ? 'transaction-amount-positive' : 'transaction-amount-negative'; ?>">
                                                                    <?php echo htmlspecialchars($transaction['currency'] . ' ' . number_format($transaction['amount'], 2)); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <div class="text-wrap" style="max-width: 250px;">
                                                                    <?php echo htmlspecialchars($transaction['notes']); ?>
                                                                    <small class="d-block text-muted mt-1">By: <?php echo htmlspecialchars($transaction['created_by']); ?></small>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <!-- End Recent Transactions -->
                        </div>
                    </div>
                    <?php endif; ?>
                </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="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize flatpickr for date inputs
            flatpickr(".flatpickr-date", {
                dateFormat: "Y-m-d",
                allowInput: true
            });
            
            // Initialize Select2
            $('.select2').select2({
                placeholder: "Select a customer",
                allowClear: true
            });
            
            // Form validation
            const form = document.getElementById('debt-adjustment-form');
            if (form) {
                form.addEventListener('submit', function(event) {
                    let isValid = true;
                    const amount = form.querySelector('input[name="amount"]');
                    const currency = form.querySelector('select[name="currency"]');
                    const notes = form.querySelector('textarea[name="notes"]');
                    
                    // Reset previous validation
                    form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
                    
                    // Validate amount
                    if (!amount.value || parseFloat(amount.value) === 0) {
                        amount.classList.add('is-invalid');
                        isValid = false;
                    }
                    
                    // Validate currency
                    if (!currency.value) {
                        currency.classList.add('is-invalid');
                        isValid = false;
                    }
                    
                    // Validate notes
                    if (!notes.value.trim()) {
                        notes.classList.add('is-invalid');
                        isValid = false;
                    }
                    
                    if (!isValid) {
                        event.preventDefault();
                        alert('Please fill in all required fields correctly.');
                    }
                });
            }
        });
    </script>
</body>

</html>