<?php
/**
 * ajax/upload_final_file.php
 * Handles: declaration_form, final_manuscript_revised, resubmission, payment_receipt
 */
error_reporting(0);
header('Content-Type: application/json');

require_once __DIR__ . '/../config/db.php';
startSession();
$user = getCurrentUser();
if (!$user) { echo json_encode(['success'=>false,'message'=>'Not logged in']); exit; }

$user_id       = $user['user_id'];
$submission_id = (int)($_POST['submission_id'] ?? 0);
$file_type     = $_POST['file_type'] ?? '';
$reference_no  = trim($_POST['reference_no'] ?? ''); // bank transfer reference (optional for non-payment types)

$allowed_types = ['declaration_form','final_manuscript_revised','resubmission','payment_receipt'];
if (!$submission_id || !in_array($file_type, $allowed_types)) {
    echo json_encode(['success'=>false,'message'=>'Invalid request']); exit;
}

// Verify submission belongs to this user
try {
    $chk = db()->prepare("SELECT submission_id FROM submissions WHERE submission_id=? AND user_id=?");
    $chk->execute([$submission_id, $user_id]);
    if (!$chk->fetch()) {
        echo json_encode(['success'=>false,'message'=>'Submission not found']); exit;
    }
} catch(PDOException $e) {
    echo json_encode(['success'=>false,'message'=>'DB error']); exit;
}

// File validation
if (empty($_FILES['file']['tmp_name'])) {
    echo json_encode(['success'=>false,'message'=>'No file uploaded']); exit;
}

// payment_receipt allows images too; others are doc-only
$maxSize = ($file_type === 'payment_receipt') ? 5 * 1024 * 1024 : 10 * 1024 * 1024;
if ($_FILES['file']['size'] > $maxSize) {
    $limit = ($file_type === 'payment_receipt') ? '5MB' : '10MB';
    echo json_encode(['success'=>false,'message'=>"File too large (max $limit)"]); exit;
}

$ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));

$allowedExts = [
    'declaration_form'         => ['doc','docx'],
    'final_manuscript_revised' => ['doc','docx'],
    'resubmission'             => ['doc','docx'],
    'payment_receipt'          => ['jpg','jpeg','png','pdf','doc','docx'],
];
if (!in_array($ext, $allowedExts[$file_type])) {
    $allowed = implode(', ', array_map('strtoupper', $allowedExts[$file_type]));
    echo json_encode(['success'=>false,'message'=>"Invalid file type. Allowed: $allowed"]); exit;
}

// For payment_receipt require a reference number
if ($file_type === 'payment_receipt' && $reference_no === '') {
    echo json_encode(['success'=>false,'message'=>'Transaction / reference number is required']); exit;
}

// Upload path
$uploadDir = __DIR__ . '/../uploads/final_submissions/' . $submission_id . '/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

$safeOriginal = preg_replace('/[^a-zA-Z0-9._-]/', '_', $_FILES['file']['name']);
$storedName   = time() . '_' . $file_type . '_' . $safeOriginal;
$storedPath   = 'uploads/final_submissions/' . $submission_id . '/' . $storedName;
$fullPath     = $uploadDir . $storedName;

if (!move_uploaded_file($_FILES['file']['tmp_name'], $fullPath)) {
    echo json_encode(['success'=>false,'message'=>'File save failed']); exit;
}

// Persist to DB
try {
    $exists = db()->prepare(
        "SELECT file_id FROM submission_files WHERE submission_id=? AND file_type=?"
    );
    $exists->execute([$submission_id, $file_type]);
    $row = $exists->fetch();

    $mime   = $_FILES['file']['type'];
    $sizeKb = (int)($_FILES['file']['size'] / 1024);

    if ($row) {
        $upd = db()->prepare(
            "UPDATE submission_files
             SET original_name=?, stored_path=?, mime_type=?, file_size_kb=?, uploaded_at=NOW()
             WHERE submission_id=? AND file_type=?"
        );
        $upd->execute([$_FILES['file']['name'], $storedPath, $mime, $sizeKb, $submission_id, $file_type]);
    } else {
        $ins = db()->prepare(
            "INSERT INTO submission_files
             (submission_id, file_type, original_name, stored_path, mime_type, file_size_kb, uploaded_at)
             VALUES (?,?,?,?,?,?,NOW())"
        );
        $ins->execute([$submission_id, $file_type, $_FILES['file']['name'], $storedPath, $mime, $sizeKb]);
    }

    // If resubmission, reset status to submitted for re-review
    if ($file_type === 'resubmission') {
        db()->prepare(
            "UPDATE submissions SET submission_status='submitted', updated_at=NOW() WHERE submission_id=?"
        )->execute([$submission_id]);
    }

    // If payment_receipt (bank transfer), log a pending payment record
    if ($file_type === 'payment_receipt') {
        // Fetch tracking code for this submission
        $tRow = db()->prepare("SELECT tracking_code FROM submissions WHERE submission_id=?");
        $tRow->execute([$submission_id]);
        $tracking = $tRow->fetchColumn() ?: '';

        // Build a unique invoice number
        $invoiceNo = 'BANK-' . strtoupper($tracking ?: $submission_id) . '-' . time();

        $pIns = db()->prepare(
            "INSERT INTO payments
             (submission_id, tracking_code, invoice_no, gateway, gateway_order_id, status,
              payer_email, payer_name, amount, currency, created_at, updated_at)
             VALUES (?, ?, ?, 'bank', ?, 'PENDING_VERIFICATION',
                     ?, ?, 0.00, 'USD', NOW(), NOW())"
        );
        $pIns->execute([
            $submission_id,
            $tracking,
            $invoiceNo,
            $reference_no,                          // stored in gateway_order_id as the bank ref
            $user['email'] ?? '',
            trim(($user['first_name']??'') . ' ' . ($user['last_name']??'')),
        ]);
    }

    echo json_encode([
        'success'   => true,
        'message'   => $file_type === 'payment_receipt'
                        ? 'Payment slip submitted! Our team will verify it shortly.'
                        : 'File uploaded successfully',
        'path'      => $storedPath,
        'file_type' => $file_type,
    ]);

} catch(PDOException $e) {
    @unlink($fullPath);
    echo json_encode(['success'=>false,'message'=>'Database error: '.$e->getMessage()]);
}