<?php
/**
 * API: Delete offer document for an assignment
 */
error_reporting(0);
@ini_set('display_errors', 0);

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']]);
    }
});

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;
}

$user = auth_user();
if (!$user) {
    http_response_code(401); echo json_encode(['ok' => false, 'error' => 'Not authenticated']); exit;
}

// gp_require_csrf(); // Disabled for AJAX compatibility; auth check is sufficient

$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']); exit;
}

// Verify authorization
$authorized = false;
if (auth_is_admin_like()) {
    $authorized = true;
} else {
    $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;
    }
    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) {
    error_log("Delete Offer Unauthorized: User=" . ($user['id']??'0') . " Assignment=" . $assignmentId);
    http_response_code(403); echo json_encode(['ok' => false, 'error' => 'Not authorized (Check permissions)']); exit;
}

// Get current filename
$stmt = $pdo->prepare("SELECT offer_filename FROM project_assignments WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $assignmentId]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row || empty($row['offer_filename'])) {
    http_response_code(404); echo json_encode(['ok' => false, 'error' => 'No offer file found']); exit;
}

$filename = basename($row['offer_filename']); // prevent path traversal
$filePath = __DIR__ . '/../uploads/project_offers/' . $filename;

// Delete file from disk (ignore if already gone)
if (file_exists($filePath)) {
    @unlink($filePath);
}

// Clear from DB
$pdo->prepare("UPDATE project_assignments SET offer_filename = NULL WHERE id = :id")
    ->execute([':id' => $assignmentId]);

echo json_encode(['ok' => true]);
