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

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

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

// Get user details and verify permissions
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, role_id FROM users WHERE user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param('i', $user_id);
$stmt_user->execute();
$result_user = $stmt_user->get_result();

if ($result_user->num_rows === 0) {
    $_SESSION['error_message'] = "User not found";
    header('Location: file_list.php');
    exit();
}

$user = $result_user->fetch_assoc();
$username = $user['username'];
$role_id = $user['role_id'];

// Verify user has invoice permissions
if (!hasPermission($role_id, 'invoice')) {
    $_SESSION['error_message'] = "You don't have permission to record payments";
    header('Location: file_list.php');
    exit();
}

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['record_payment'])) {
    $_SESSION['error_message'] = "Invalid request";
    header('Location: file_list.php');
    exit();
}

// Get payment details from POST
$invoice_id = isset($_POST['invoice_id']) ? intval($_POST['invoice_id']) : 0;
$payment_date = isset($_POST['payment_date']) ? $_POST['payment_date'] : date('Y-m-d');
$amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
$payment_method = isset($_POST['payment_method']) ? $_POST['payment_method'] : '';
$reference_number = isset($_POST['reference_number']) ? $_POST['reference_number'] : '';
$notes = isset($_POST['notes']) ? $_POST['notes'] : '';

// Validate input
if ($invoice_id <= 0 || $amount <= 0 || empty($payment_method)) {
    $_SESSION['error_message'] = "Invalid payment details";
    header("Location: view_invoice.php?id=$invoice_id");
    exit();
}

// Get invoice details to verify it exists and get file number
$invoice_query = "SELECT i.*, f.id as file_id
                 FROM invoices i 
                 LEFT JOIN files f ON i.file_number = f.file_number
                 WHERE i.invoice_id = ?";
$invoice_stmt = $conn->prepare($invoice_query);
$invoice_stmt->bind_param('i', $invoice_id);
$invoice_stmt->execute();
$invoice_result = $invoice_stmt->get_result();

if ($invoice_result->num_rows === 0) {
    $_SESSION['error_message'] = "Invoice not found";
    header('Location: file_list.php');
    exit();
}

$invoice = $invoice_result->fetch_assoc();
$file_id = $invoice['file_id'];
$file_number = $invoice['file_number'];
$total_amount = $invoice['total_amount'];
$current_status = $invoice['status'];

// Start transaction
$conn->begin_transaction();

try {
    // 1. Insert payment record
    $payment_query = "INSERT INTO invoice_payments (
        invoice_id, payment_date, amount, payment_method, 
        reference_number, notes, recorded_by, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
    
    $payment_stmt = $conn->prepare($payment_query);
    if (!$payment_stmt) {
        throw new Exception("Failed to prepare payment statement: " . $conn->error);
    }
    
    $payment_stmt->bind_param(
        'isdssis',
        $invoice_id,
        $payment_date,
        $amount,
        $payment_method,
        $reference_number,
        $notes,
        $user_id
    );
    
    if (!$payment_stmt->execute()) {
        throw new Exception("Failed to record payment: " . $payment_stmt->error);
    }
    
    // 2. Check if payment equals or exceeds total and update invoice status if needed
    if ($current_status !== 'paid' && $amount >= $total_amount) {
        $update_status_query = "UPDATE invoices SET status = 'paid', updated_at = NOW() WHERE invoice_id = ?";
        $update_status_stmt = $conn->prepare($update_status_query);
        
        if (!$update_status_stmt) {
            throw new Exception("Failed to prepare status update statement: " . $conn->error);
        }
        
        $update_status_stmt->bind_param('i', $invoice_id);
        
        if (!$update_status_stmt->execute()) {
            throw new Exception("Failed to update invoice status: " . $update_status_stmt->error);
        }
    }
    
    // 3. Create notification
    $notif_message = "Payment of $amount recorded for invoice {$invoice['invoice_number']} by {$username}.";
    $notif_query = "INSERT INTO notifications (file_id, file_number, notif_message, notif_message_id, created_at) 
                    VALUES (?, ?, ?, 2, NOW())";
    
    $notif_stmt = $conn->prepare($notif_query);
    if ($notif_stmt) {
        $notif_message_id = 2; // Assuming 2 is for updates, adjust if needed
        $notif_stmt->bind_param('isi', $file_id, $file_number, $notif_message, $notif_message_id);
        $notif_stmt->execute(); // We don't throw exception if this fails as it's not critical
    }
    
    // Commit the transaction
    $conn->commit();
    
    $_SESSION['success_message'] = "Payment recorded successfully";
} catch (Exception $e) {
    // Rollback the transaction
    $conn->rollback();
    $_SESSION['error_message'] = "Error recording payment: " . $e->getMessage();
}

// Redirect back to invoice view
header("Location: view_invoice.php?id=$invoice_id");
exit();
?>