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

// 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]);
