<?php
/**
 * API: Mark assignment as complete and notify admin (AJAX endpoint)
 */
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';
$pdo = crm_pdo();

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

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

gp_require_csrf();

$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;
$userLabel = '';
$user = auth_user();
if ($user) {
    if (auth_is_admin_like()) {
        $authorized = true;
        $userLabel = $user['username'];
    } else {
        $userId = (int)$user['id'];
        $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;
            $userLabel = $user['username'];
        }
    }
}

if (!$authorized && function_exists('auth_partner_id')) {
    $partnerId = auth_partner_id();
    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;
            $c = $pdo->prepare("SELECT company_name FROM external_partners WHERE id = ?");
            $c->execute([$partnerId]);
            $userLabel = $c->fetchColumn() ?: 'Partner';
        }
    }
}

if (!$authorized) {
    http_response_code(403); echo json_encode(['ok'=>false,'error'=>'Not authorized']); exit;
}

// Get assignment info to check partner constraint
$stmtAss = $pdo->prepare("SELECT project_id, external_partner_id FROM project_assignments WHERE id = ?");
$stmtAss->execute([$assignmentId]);
$ass = $stmtAss->fetch(PDO::FETCH_ASSOC);

if ($ass && !empty($ass['external_partner_id'])) {
    $pId = (int)$ass['project_id'];
    $partId = (int)$ass['external_partner_id'];

    // 1. Check if partner submitted a costing/quote
    $stmtCost = $pdo->prepare("SELECT quote_amount FROM partner_project_costings WHERE project_id = ? AND external_partner_id = ? LIMIT 1");
    $stmtCost->execute([$pId, $partId]);
    $quoteVal = $stmtCost->fetchColumn();
    if ($quoteVal === false || (float)$quoteVal <= 0) {
        echo json_encode(['ok' => false, 'error' => 'Πρέπει να υποβάλετε την προσφορά / κοστολόγιό σας πριν την ολοκλήρωση.']);
        exit;
    }

    // 2. Check if project budget is defined
    $stmtProj = $pdo->prepare("SELECT budget FROM projects WHERE id = ?");
    $stmtProj->execute([$pId]);
    $budgetVal = (float)$stmtProj->fetchColumn();
    if ($budgetVal <= 0) {
        echo json_encode(['ok' => false, 'error' => 'Δεν έχει οριστεί η χρέωση (budget) του έργου από τη διαχείριση.']);
        exit;
    }

    // 3. Check if project is fully paid
    $stmtPay = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) FROM project_payments WHERE project_id = ? AND payment_type IN ('deposit', 'payment')");
    $stmtPay->execute([$pId]);
    $totalPaid = (float)$stmtPay->fetchColumn();
    if ($totalPaid < $budgetVal) {
        $diff = $budgetVal - $totalPaid;
        echo json_encode(['ok' => false, 'error' => 'Το έργο δεν είναι εξοφλημένο. Υπολείπονται ακόμη €' . number_format($diff, 2) . ' για την εξόφληση.']);
        exit;
    }
}

// Update the assignment status
$stmt = $pdo->prepare("UPDATE project_assignments SET status = 'completed', stopped_at = NOW() WHERE id = :aid AND status != 'completed'");
$stmt->execute([':aid' => $assignmentId]);

if ($stmt->rowCount() > 0) {
    // Get project info for the log
    $q = $pdo->prepare("SELECT p.id, p.title FROM projects p JOIN project_assignments pa ON pa.project_id = p.id WHERE pa.id = ?");
    $q->execute([$assignmentId]);
    $pInfo = $q->fetch();
    
    if ($pInfo) {
        // Send Notification to Admin (without completing the project itself)
        gp_log_action($pdo, 'ASSIGNMENT_COMPLETE', 'project', $pInfo['id'], "Ολοκληρώθηκε η εργασία από $userLabel στο έργο " . $pInfo['title']);
        
        // Push notification to admins/managers
        $msg = "✅ Ολοκληρώθηκε εργασία από {$userLabel} στο έργο {$pInfo['title']}";
        $link = "/gopools/public/projects/view.php?id=" . (int)$pInfo['id'];
        
        $admins = $pdo->query("SELECT id FROM users WHERE role IN ('admin', 'manager')")->fetchAll(PDO::FETCH_COLUMN);
        foreach ($admins as $adminId) {
            $insNotif = $pdo->prepare("INSERT INTO user_notifications (user_id, message, link_url, is_read) VALUES (?, ?, ?, 0)");
            $insNotif->execute([$adminId, $msg, $link]);
        }
    }
}

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