<?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 user has approval permission
$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];

// Define roles that can approve
$can_approve_roles = [1, 2]; // Admin and General Manager

if (!in_array($role_id, $can_approve_roles)) {
    $_SESSION['error_message'] = "You don't have permission to perform this action.";
    header('Location: file_list.php');
    exit();
}

// Check if file number is provided via POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['file_number']) || empty($_POST['file_number'])) {
    $_SESSION['error_message'] = "Invalid request or missing file number.";
    header('Location: file_list.php');
    exit();
}

$file_number = $_POST['file_number'];

try {
    // Start transaction for data integrity
    $conn->begin_transaction();
    
    // 1. Get all records from pre_proforma for this file
    $query = "SELECT * FROM pre_proforma WHERE file_number = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('s', $file_number);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception("No pre-proforma records found for this file.");
    }
    
    // 2. Insert each record into proforma table
    $insert_query = "INSERT INTO proforma (
                        file_number, all_in, all_in_amount, category, 
                        cost_code, cost_description, charge, vatable, 
                        vat_amount, currency, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
                    
    $insert_stmt = $conn->prepare($insert_query);
    
    // Track if we've processed an all-in record
    $all_in_processed = false;
    $all_in_amount = 0;
    
    while ($row = $result->fetch_assoc()) {
        // Store all_in amount for logging
        if ($row['all_in'] === 'Yes') {
            $all_in_amount = $row['all_in_amount'];
            $all_in_processed = true;
        }
        
        $insert_stmt->bind_param(
            'ssssssdsss',
            $row['file_number'],
            $row['all_in'],
            $row['all_in_amount'],
            $row['category'],
            $row['cost_code'],
            $row['cost_description'],
            $row['charge'],
            $row['vatable'],
            $row['vat_amount'],
            $row['currency']
        );
        
        if (!$insert_stmt->execute()) {
            throw new Exception("Error inserting record into proforma: " . $insert_stmt->error);
        }
    }
    
    // 3. Delete records from pre_proforma table
    $delete_query = "DELETE FROM pre_proforma WHERE file_number = ?";
    $delete_stmt = $conn->prepare($delete_query);
    $delete_stmt->bind_param('s', $file_number);
    
    if (!$delete_stmt->execute()) {
        throw new Exception("Error deleting records from pre_proforma: " . $delete_stmt->error);
    }
    
    // 4. Log the action in system activity log (if such table exists)
    // This is optional but good for auditing
    if (isset($_SESSION['username'])) {
        $username = $_SESSION['username'];
        $action = "Converted pre-proforma to proforma";
        $details = "File: $file_number" . ($all_in_processed ? ", All-In Amount: $all_in_amount" : "");
        
        $log_query = "INSERT INTO activity_log (user_id, username, action, details, performed_at) 
                      VALUES (?, ?, ?, ?, NOW())";
        
        // Only execute if activity_log table exists
        if ($conn->query("SHOW TABLES LIKE 'activity_log'")->num_rows > 0) {
            $log_stmt = $conn->prepare($log_query);
            $log_stmt->bind_param('isss', $user_id, $username, $action, $details);
            $log_stmt->execute();
        }
    }
    
    // 5. Get the file ID for redirect
    $file_query = "SELECT id FROM files WHERE file_number = ? LIMIT 1";
    $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 {
        throw new Exception("Could not find file ID for redirection.");
    }
    
    // Commit transaction if everything went well
    $conn->commit();
    
    // Set success message and redirect
    $_SESSION['success_message'] = "Pre-proforma successfully converted to proforma invoice.";
    header("Location: view_file.php?id=$file_id");
    exit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log the error
    error_log("Error in send_to_proforma.php: " . $e->getMessage());
    
    // Get file ID for redirection if possible
    $file_id = 0;
    try {
        $file_stmt = $conn->prepare("SELECT id FROM files WHERE file_number = ? LIMIT 1");
        $file_stmt->bind_param('s', $file_number);
        $file_stmt->execute();
        $file_result = $file_stmt->get_result();
        if ($file_result->num_rows > 0) {
            $file_row = $file_result->fetch_assoc();
            $file_id = $file_row['id'];
        }
    } catch (Exception $redirect_error) {
        // If we can't get the file ID, we'll redirect to file_list.php
    }
    
    // Set error message and redirect
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    
    if ($file_id > 0) {
        header("Location: view_file.php?id=$file_id");
    } else {
        header('Location: file_list.php');
    }
    exit();
}
?>