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

$id = (int)($p['id'] ?? 0);

if ($id <= 0) {
    echo json_encode(['ok' => false, 'error' => 'Invalid ID.']);
    exit;
}

try {
    // Get project ID for logging
    $stmtP = $pdo->prepare("SELECT project_id, title FROM project_visits WHERE id = ?");
    $stmtP->execute([$id]);
    $visit = $stmtP->fetch();
    
    if (!$visit) {
        echo json_encode(['ok' => false, 'error' => 'Visit not found.']);
        exit;
    }

    $stmt = $pdo->prepare("DELETE FROM project_visits WHERE id = ?");
    $stmt->execute([$id]);
    
    gp_log_action($pdo, 'PROJECT_VISIT_DELETE', 'project', $visit['project_id'], "Deleted visit: " . $visit['title']);
    
    echo json_encode(['ok' => true]);
} catch (Exception $e) {
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
