<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();

header('Content-Type: application/json; charset=utf-8');

$p = json_decode(file_get_contents('php://input'), true);
if (!$p) $p = $_POST;

$projectId = (int)($p['project_id'] ?? 0);
$title = trim((string)($p['title'] ?? ''));
$start = trim((string)($p['start_date'] ?? ''));
$end = trim((string)($p['end_date'] ?? ''));

if ($projectId <= 0 || $title === '' || $start === '' || $end === '') {
    echo json_encode(['ok' => false, 'error' => 'All fields are required.']);
    exit;
}

try {
    $stmt = $pdo->prepare("INSERT INTO project_visits (project_id, title, start_date, end_date) VALUES (?, ?, ?, ?)");
    $stmt->execute([$projectId, $title, $start, $end]);
    $id = $pdo->lastInsertId();
    
    gp_log_action($pdo, 'PROJECT_VISIT_ADD', 'project', $projectId, "Added visit: $title");
    
    echo json_encode(['ok' => true, 'id' => $id]);
} catch (Exception $e) {
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
