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

if (!isset($_SESSION['user_id'])) {
    die(json_encode(['success' => false, 'message' => 'Not authenticated']));
}

if (!isset($_GET['file_number'])) {
    die(json_encode(['success' => false, 'message' => 'File number not provided']));
}

$file_number = $_GET['file_number'];

// Check if file exists and get its details
$sql = "SELECT f.*, 
        CASE WHEN p.id IS NOT NULL THEN 1 ELSE 0 END as in_proforma
        FROM files f
        LEFT JOIN proforma p ON f.file_number = p.file_number
        WHERE f.file_number = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $file_number);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die(json_encode(['success' => false, 'message' => 'File not found']));
}

$file = $result->fetch_assoc();

// Check if file is in proforma
if ($file['in_proforma']) {
    die(json_encode([
        'success' => true,
        'in_proforma' => true,
        'message' => 'File is already in proforma stage'
    ]));
}

// Return file details
echo json_encode([
    'success' => true,
    'in_proforma' => false,
    'all_in_amount' => $file['all_in_amount'] ?? 0,
    'file_number' => $file['file_number']
]);
?>