<?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 this is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request method";
    header('Location: client_debt_management.php');
    exit();
}

// Check if required data is provided
if (!isset($_POST['customer_id']) || !isset($_POST['currency']) || !isset($_POST['credit_limit'])) {
    $_SESSION['error_message'] = "Missing required data";
    header('Location: client_debt_management.php');
    exit();
}

// 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()) {
    $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 edit
$can_edit = hasPermission($role_id, 'edit') || hasPermission($role_id, 'approve');

if (!$can_edit) {
    $_SESSION['error_message'] = "You don't have permission to update credit limits";
    header('Location: client_debt_management.php');
    exit();
}

// Get form data
$customer_id = intval($_POST['customer_id']);
$currency = $_POST['currency'];
$credit_limit = floatval($_POST['credit_limit']);

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

// Update credit limit
$success = $debtController->updateCreditLimit($customer_id, $currency, $credit_limit);

if ($success) {
    $_SESSION['success_message'] = "Credit limit updated successfully";
    
    // Log the activity
    $operation = $credit_limit > 0 ? "Credit limit set to {$currency} {$credit_limit}" : "Credit limit removed";
    $logSql = "INSERT INTO user_activity_log (user_id, activity_type, description, affected_table, affected_id, created_at)
               VALUES (?, 'update_credit_limit', ?, 'client_debts', ?, NOW())";
    
    $logStmt = $conn->prepare($logSql);
    $logStmt->bind_param('isi', $user_id, $operation, $customer_id);
    $logStmt->execute();
    
    // Redirect back to view client debt page
    header("Location: view_client_debt.php?id={$customer_id}&currency={$currency}");
} else {
    $_SESSION['error_message'] = "Failed to update credit limit";
    header("Location: view_client_debt.php?id={$customer_id}&currency={$currency}");
}
exit();
?>