<?php
/**
 * API: Submit a duration suggestion for a project assignment.
 * Called via POST from employee/partner portal.
 */
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';
auth_require_login();
$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();

$projectId    = (int)($_POST['project_id'] ?? 0);
$assignmentId = (int)($_POST['assignment_id'] ?? 0) ?: null;
$startDate    = trim((string)($_POST['proposed_start_date'] ?? ''));
$endDate      = trim((string)($_POST['proposed_end_date'] ?? ''));
$days         = trim((string)($_POST['proposed_days'] ?? ''));
$notes        = trim((string)($_POST['notes'] ?? ''));
$byType       = trim((string)($_POST['by_type'] ?? 'employee'));

if ($projectId <= 0) {
    http_response_code(422); echo json_encode(['ok'=>false,'error'=>'Missing project ID']); exit;
}

if (!in_array($byType, ['employee','partner'], true)) $byType = 'employee';

// Safety: verify the user is actually linked to this assignment
$userId = (int)(auth_user()['id'] ?? 0);

// Calculate days from dates if not given
if ($startDate && $endDate && $days === '') {
    $d1 = new DateTime($startDate);
    $d2 = new DateTime($endDate);
    $diff = (int)$d1->diff($d2)->days;
    $days = $diff;
} else {
    $days = $days !== '' ? (int)$days : null;
}

$stmt = $pdo->prepare("
    INSERT INTO project_duration_suggestions
        (project_id, assignment_id, suggested_by_user_id, suggested_by_type,
         proposed_start_date, proposed_end_date, proposed_days, notes, status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')
");
$stmt->execute([
    $projectId,
    $assignmentId,
    $userId,
    $byType,
    $startDate ?: null,
    $endDate   ?: null,
    $days,
    $notes ?: null,
]);

echo json_encode(['ok' => true, 'id' => $pdo->lastInsertId()]);
