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

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

// Check if the request is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: file_list.php');
    exit();
}

// Check required parameters
if (!isset($_POST['file_number']) || empty($_POST['file_number'])) {
    $_SESSION['error_message'] = "No file number provided";
    header('Location: file_list.php');
    exit();
}

$file_number = $_POST['file_number'];
$file_id = $_POST['file_id'] ?? null;

// Get file details to ensure it exists
$file_query = "SELECT id, currency FROM files WHERE file_number = ?";
$file_stmt = $conn->prepare($file_query);
$file_stmt->bind_param('s', $file_number);
$file_stmt->execute();
$file_result = $file_stmt->get_result();

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

$file = $file_result->fetch_assoc();
if (!$file_id) {
    $file_id = $file['id'];
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Delete existing pre_proforma records for this file
    $delete_query = "DELETE FROM pre_proforma WHERE file_number = ?";
    $delete_stmt = $conn->prepare($delete_query);
    $delete_stmt->bind_param('s', $file_number);
    $delete_stmt->execute();
    
    // Get submitted data
    $all_in = $_POST['allin'] ?? 'No';
    $all_in_amount = ($all_in === 'Yes') ? floatval($_POST['all_in_amount']) : null;
    $currency = $_POST['currency'] ?? $file['currency'];
    
    // Insert agency fee (operational cost)
    $agency_fees = floatval($_POST['agency_fees'] ?? 0);
    $vatable = $_POST['vatable'] ?? 'No';
    $vat_amount = ($vatable === 'Yes') ? floatval($_POST['vat'] ?? 0) : 0;
    
    $operational_sql = "INSERT INTO pre_proforma (
                            file_number, all_in, all_in_amount, category, 
                            cost_code, cost_description, charge, vatable, 
                            vat_amount, currency, created_at
                        ) VALUES (?, ?, ?, 'Operational', '1-101', 'Agency Fee', ?, ?, ?, ?, NOW())";
    
    $operational_stmt = $conn->prepare($operational_sql);
    $operational_stmt->bind_param(
        'ssddsss',
        $file_number, $all_in, $all_in_amount, $agency_fees, 
        $vatable, $vat_amount, $currency
    );
    $operational_stmt->execute();
    
    // Insert non-operational costs
    if (isset($_POST['cost_reference']) && is_array($_POST['cost_reference'])) {
        $cost_references = $_POST['cost_reference'];
        $charges = $_POST['charge'];
        
        $non_op_sql = "INSERT INTO pre_proforma (
                            file_number, all_in, all_in_amount, category, 
                            cost_code, cost_description, charge, vatable, 
                            vat_amount, currency, created_at
                        ) VALUES (?, NULL, NULL, 'Non-Operational', ?, ?, ?, 'No', 0, ?, NOW())";
        
        $non_op_stmt = $conn->prepare($non_op_sql);
        
        foreach ($cost_references as $i => $cost_code) {
            if (empty($cost_code) || empty($charges[$i])) continue;
            
            // Get cost description
            $desc_query = "SELECT description FROM cost_reference WHERE code = ? LIMIT 1";
            $desc_stmt = $conn->prepare($desc_query);
            $desc_stmt->bind_param('s', $cost_code);
            $desc_stmt->execute();
            $desc_result = $desc_stmt->get_result();
            $cost_description = ($desc_result->num_rows > 0) 
                ? $desc_result->fetch_assoc()['description'] 
                : '';
            
            $charge_amount = floatval($charges[$i]);
            
            $non_op_stmt->bind_param(
                'sssds',
                $file_number, $cost_code, $cost_description, 
                $charge_amount, $currency
            );
            $non_op_stmt->execute();
        }
    }
    
    $conn->commit();
    
    // Success message and redirect
    $_SESSION['success_message'] = "Pre-proforma charges saved successfully";
    header('Location: view_file.php?id=' . $file_id . '#pre-proforma');
    exit();
    
} catch (Exception $e) {
    // Rollback the transaction if an error occurs
    $conn->rollback();
    
    $_SESSION['error_message'] = "Error saving pre-proforma: " . $e->getMessage();
    header('Location: view_file.php?id=' . $file_id);
    exit();
}
?>