<?php
/**
 * API: Upload offer document for an assignment (AJAX endpoint)
 */

// Must be FIRST — suppress PHP errors/notices from breaking JSON output
error_reporting(0);
@ini_set('display_errors', 0);

// Catch any fatal/uncaught error and return JSON
register_shutdown_function(function () {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        if (!headers_sent()) {
            http_response_code(500);
            header('Content-Type: application/json');
        }
        echo json_encode(['ok' => false, 'error' => 'Server error: ' . $err['message'] . ' in ' . basename($err['file']) . ':' . $err['line']]);
    }
});

require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
    exit;
}

// Auth check — return JSON (never redirect from an API)
$user = auth_user();
if (!$user) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Not authenticated. Please refresh the page.']);
    exit;
}

$pdo = crm_pdo();

$assignmentId = (int)($_POST['assignment_id'] ?? 0);
if ($assignmentId <= 0) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => 'Missing assignment_id. Got: ' . json_encode($_POST)]);
    exit;
}

// Verify authorization
$authorized = false;

if (auth_is_admin_like()) {
    $authorized = true;
} else {
    // Check partner
    $partnerId = function_exists('auth_partner_id') ? auth_partner_id() : 0;
    if ($partnerId > 0) {
        $stmt = $pdo->prepare("SELECT id FROM project_assignments WHERE id = :id AND external_partner_id = :pid LIMIT 1");
        $stmt->execute([':id' => $assignmentId, ':pid' => $partnerId]);
        if ($stmt->fetch()) $authorized = true;
    }

    // Check employee
    if (!$authorized) {
        $userId = (int)($user['id'] ?? 0);
        if ($userId > 0) {
            $stmt = $pdo->prepare("SELECT id FROM project_assignments WHERE id = :id AND employee_id = (SELECT employee_id FROM users WHERE id = :uid LIMIT 1) LIMIT 1");
            $stmt->execute([':id' => $assignmentId, ':uid' => $userId]);
            if ($stmt->fetch()) $authorized = true;
        }
    }
}

if (!$authorized) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Not authorized for assignment #' . $assignmentId . '. Partner ID: ' . ($partnerId ?? 'n/a')]);
    exit;
}

// File check
if (empty($_FILES['offer_file']) || $_FILES['offer_file']['error'] !== UPLOAD_ERR_OK) {
    $errCode = $_FILES['offer_file']['error'] ?? 99;
    $errMessages = [
        1 => 'File too large (server php.ini limit)',
        2 => 'File too large (form MAX_FILE_SIZE)',
        3 => 'File only partially uploaded',
        4 => 'No file uploaded',
        6 => 'Missing temp folder',
        7 => 'Failed to write to disk (permissions)',
    ];
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => $errMessages[$errCode] ?? "Upload error code: $errCode"]);
    exit;
}

$file = $_FILES['offer_file'];
$ext  = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'png', 'jpg', 'jpeg'];

if (!in_array($ext, $allowed, true)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'File type .' . $ext . ' not allowed.']);
    exit;
}

// Save to uploads/project_offers
$uploadDir = __DIR__ . '/../uploads/project_offers';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}
if (!is_dir($uploadDir)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Upload dir does not exist: ' . $uploadDir]);
    exit;
}

$stored = 'offer_' . $assignmentId . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
$dest   = $uploadDir . DIRECTORY_SEPARATOR . $stored;

if (!move_uploaded_file($file['tmp_name'], $dest)) {
    http_response_code(500);
    echo json_encode([
        'ok'    => false,
        'error' => 'Could not save file. Dir: ' . $uploadDir
                 . ' | writable: ' . (is_writable($uploadDir) ? 'YES' : 'NO')
                 . ' | tmp: ' . $file['tmp_name']
    ]);
    exit;
}

// Update DB
$pdo->prepare("UPDATE project_assignments SET offer_filename = :fname WHERE id = :aid")
    ->execute([':aid' => $assignmentId, ':fname' => $stored]);

echo json_encode(['ok' => true, 'filename' => $stored]);
