<?php
/**
 * API: Handle project visits (add/delete)
 */
require_once __DIR__ . '/../../app/core/bootstrap.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();

$action    = trim((string)($_POST['action'] ?? ''));
$projectId = (int)($_POST['project_id'] ?? 0);

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

if ($action === 'add') {
    $title = trim((string)($_POST['title'] ?? ''));
    $start = trim((string)($_POST['start_date'] ?? ''));
    $end   = trim((string)($_POST['end_date'] ?? ''));

    if ($title === '') { echo json_encode(['ok'=>false,'error'=>'Title is required']); exit; }
    if ($start === '') { echo json_encode(['ok'=>false,'error'=>'Start date is required']); exit; }
    if ($end === '') $end = $start;

    $stmt = $pdo->prepare("INSERT INTO project_visits (project_id, title, start_date, end_date) VALUES (?, ?, ?, ?)");
    $stmt->execute([$projectId, $title, $start, $end]);
    
    echo json_encode(['ok' => true]);
} 
elseif ($action === 'delete') {
    $visitId = (int)($_POST['visit_id'] ?? 0);
    $stmt = $pdo->prepare("DELETE FROM project_visits WHERE id = ? AND project_id = ?");
    $stmt->execute([$visitId, $projectId]);
    
    echo json_encode(['ok' => true]);
} 
else {
    echo json_encode(['ok'=>false,'error'=>'Invalid action']);
}
