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

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

// Get user ID and role for authorization
$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];

// Check if the user has permission to create a proforma
$allowed_roles = [1, 2, 3, 4]; // Admin, General Manager, Operations, Finance
if (!in_array($role_id, $allowed_roles)) {
    $_SESSION['error_message'] = "You don't have permission to create proforma invoices";
    header('Location: file_list.php');
    exit();
}

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

$file_number = $_GET['file_number'];

// Get file ID for redirect
$file_query = "SELECT id 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();
$file_id = 0;

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

// Check if pre-proforma exists
$check_query = "SELECT COUNT(*) as count FROM pre_proforma WHERE file_number = ?";
$check_stmt = $conn->prepare($check_query);
$check_stmt->bind_param('s', $file_number);
$check_stmt->execute();
$check_result = $check_stmt->get_result();
$pre_proforma_count = $check_result->fetch_assoc()['count'];

if ($pre_proforma_count == 0) {
    $_SESSION['error_message'] = "No pre-proforma data found for this file";
    header('Location: view_file.php?id=' . $file_id);
    exit();
}

// Check if proforma already exists
$proforma_query = "SELECT COUNT(*) as count FROM proforma WHERE file_number = ?";
$proforma_stmt = $conn->prepare($proforma_query);
$proforma_stmt->bind_param('s', $file_number);
$proforma_stmt->execute();
$proforma_result = $proforma_stmt->get_result();
$proforma_count = $proforma_result->fetch_assoc()['count'];

if ($proforma_count > 0) {
    $_SESSION['error_message'] = "A proforma invoice already exists for this file";
    header('Location: view_file.php?id=' . $file_id . '#proforma');
    exit();
}

try {
    $conn->begin_transaction();
    
    // Copy data from pre_proforma to proforma
    $copy_sql = "INSERT INTO proforma 
                (file_number, all_in, all_in_amount, category, cost_code, cost_description, 
                 charge, vatable, vat_amount, currency, created_at) 
                SELECT 
                 file_number, all_in, all_in_amount, category, cost_code, cost_description, 
                 charge, vatable, vat_amount, currency, NOW() 
                FROM pre_proforma 
                WHERE file_number = ?";
    
    $copy_stmt = $conn->prepare($copy_sql);
    $copy_stmt->bind_param('s', $file_number);
    $copy_stmt->execute();
    
    // Update file status if needed (optional)
    // $update_file_sql = "UPDATE files SET status = 'Proforma Created' WHERE file_number = ?";
    // $update_file_stmt = $conn->prepare($update_file_sql);
    // $update_file_stmt->bind_param('s', $file_number);
    // $update_file_stmt->execute();
    
    // Log this action
    $log_sql = "INSERT INTO user_activity_log (user_id, activity_type, file_number, description, created_at) 
               VALUES (?, 'proforma_created', ?, 'Created proforma invoice from pre-proforma data', NOW())";
    $log_stmt = $conn->prepare($log_sql);
    $log_stmt->bind_param('is', $user_id, $file_number);
    $log_stmt->execute();
    
    $conn->commit();
    
    $_SESSION['success_message'] = "Proforma invoice created successfully";
    header('Location: view_file.php?id=' . $file_id . '#proforma');
    exit();
    
} catch (Exception $e) {
    $conn->rollback();
    $_SESSION['error_message'] = "Error creating proforma invoice: " . $e->getMessage();
    header('Location: view_file.php?id=' . $file_id);
    exit();
}
?>