<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
error_reporting(0); // Hide warnings so they don't break the JSON response

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request']);
    exit;
}

$action = $_POST['action'] ?? 'stage';
$assetCode = $_POST['asset_code'] ?? 'UNKNOWN_ASSET';
$userEmail = $_POST['user_email'] ?? '';
$adminEmail = 'info@pcrr-jwt.it'; 
$brokerEmail = 'broker@pcrr-jwt.eu';

$safeCode = preg_replace('/[^a-zA-Z0-9_-]/', '', $assetCode);
$cleanFileName = $safeCode . '.pdf';

$targetDirClean = __DIR__ . '/store_bp_NFW_NFT/';
$targetDirLog = __DIR__ . '/store_logs/';

if (!file_exists($targetDirClean)) mkdir($targetDirClean, 0755, true);
if (!file_exists($targetDirLog)) mkdir($targetDirLog, 0755, true);

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$domainName = $_SERVER['HTTP_HOST'];
$scriptDir = rtrim(dirname($_SERVER['REQUEST_URI']), '/\\');
$baseUrl = $protocol . $domainName . $scriptDir;

// ==========================================
// STEP 1: STAGE UPLOAD & SEND OTP TO USER
// ==========================================
if ($action === 'stage') {
    if (!isset($_FILES['receipt_file']) || $_FILES['receipt_file']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'error' => 'File upload failed.']);
        exit;
    }

    $mockHash = md5(uniqid(rand(), true));
    $hashedFileName = $safeCode . '_' . $mockHash . '.pdf';
    $logFilePath = $targetDirLog . $hashedFileName;

    if (!move_uploaded_file($_FILES['receipt_file']['tmp_name'], $logFilePath)) {
        echo json_encode(['success' => false, 'error' => 'Failed to save temporary log file.']);
        exit;
    }

    $otp = sprintf("%06d", mt_rand(100000, 999999));

    // Send OTP to the USER so they can verify their own upload
    if (!empty($userEmail)) {
        $subject = "Verify Upload OTP: " . $assetCode;
        $headers = "From: dream.zone@pcrr-jwt.eu\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
        
        $body = "A new receipt upload is pending for Asset: " . $assetCode . "\r\n\r\n";
        $body .= "OTP CODE: " . $otp . "\r\n\r\n";
        $body .= "Please enter this in the portal to finalize the consistency check.";

        mail($userEmail, $subject, $body, $headers);
    }

    echo json_encode([
        'success' => true,
        'otp' => $otp,
        'tempFileName' => $hashedFileName
    ]);
    exit;
}

// ==========================================
// STEP 2: FINALIZE & SEND NOTIFICATIONS
// ==========================================
if ($action === 'finalize') {
    $tempFileName = $_POST['temp_file_name'] ?? '';
    
    $logFilePath = $targetDirLog . $tempFileName;
    $cleanFilePath = $targetDirClean . $cleanFileName;

    $linkClean = $baseUrl . '/store_bp_NFW_NFT/' . $cleanFileName;
    $linkLog = $baseUrl . '/store_logs/' . $tempFileName;

    if (file_exists($cleanFilePath)) {
        // CONFLICT LOGIC: Asset already exists
        $subject = "CONFLICT ALERT: Duplicate Asset " . $assetCode;
        $headers = "From: alert@pcrr-jwt.eu\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

        $body = "A duplicate upload was attempted for Asset: " . $assetCode . "\r\n\r\n";
        $body .= "The system has safely paused the overwrite to protect the original asset.\r\n\r\n";
        $body .= "Please review both versions to determine the correct procedure:\r\n";
        $body .= "1. EXISTING VAULTED FILE: " . $linkClean . "\r\n";
        $body .= "2. NEW ATTEMPTED UPLOAD: " . $linkLog . "\r\n\r\n";
        $body .= "All three parties are receiving this alert for manual resolution and corrections.";

        mail($adminEmail, $subject, $body, $headers);
        mail($brokerEmail, $subject, $body, $headers);
        if ($userEmail) mail($userEmail, $subject, $body, $headers);

        echo json_encode([
            'success' => true,
            'status' => 'conflict',
            'message' => 'Conflict logged. Emails sent to all parties.',
            'storeLink' => $linkClean
        ]);
        exit;
    } else {
        // SUCCESS LOGIC: Clean Save
        copy($logFilePath, $cleanFilePath);
        
        $subject = "Asset Vaulted Successfully: " . $assetCode;
        $headers = "From: dream.zone@pcrr-jwt.eu\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

        $body = "The transaction and receipt for asset " . $assetCode . " have been vaulted.\r\n\r\n";
        $body .= "Clean Vault File: " . $cleanFileName . "\r\n";
        $body .= "HASH Log Reference: " . $tempFileName . "\r\n";
        $body .= "Final Store Link: " . $linkClean . "\r\n\r\n";

        mail($adminEmail, $subject, $body, $headers);
        mail($brokerEmail, $subject, $body, $headers);
        if ($userEmail) mail($userEmail, $subject, $body, $headers);

        echo json_encode([
            'success' => true,
            'status' => 'saved',
            'hashedFileName' => $cleanFileName,
            'storeLink' => $linkClean
        ]);
        exit;
    }
}
?>