<?php
/**
 * detection_api.php
 * Backend API for the Detection Management Page
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// ─── Database Config ──────────────────────────────────────────────────────────
define('DB_HOST', 'localhost');
define('DB_NAME', 'i4urunplace_xml');
define('DB_USER', 'i4urunplace_xml');
define('DB_PASS', 'SEMZtyETGL8B');
define('PER_PAGE', 20);

// ─── Router ───────────────────────────────────────────────────────────────────
try {
    $pdo = connectDB();

    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input  = json_decode(file_get_contents('php://input'), true) ?: [];
        $action = $input['action'] ?? '';

        switch ($action) {
            case 'update_status':
                echo json_encode(updateStatus($pdo, $input));
                break;
            default:
                echo json_encode(['success' => false, 'error' => 'Unknown POST action']);
        }

    } else {
        $action = $_GET['action'] ?? '';

        switch ($action) {
            case 'get_detections':
                echo json_encode(getDetections($pdo));
                break;
            case 'get_detection_details':
                echo json_encode(getDetectionDetails($pdo, (int)($_GET['id'] ?? 0)));
                break;
            case 'get_stats':
                echo json_encode(['success' => true, 'stats' => getStats($pdo)]);
                break;
            default:
                echo json_encode(['success' => false, 'error' => 'Unknown action']);
        }
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

// ─── Database Connection ──────────────────────────────────────────────────────
function connectDB(): PDO {
    $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]);
    return $pdo;
}

// ─── Get Stats ────────────────────────────────────────────────────────────────
function getStats(PDO $pdo): array {
    $row = $pdo->query("
        SELECT
            COUNT(*) AS total,
            SUM(CASE WHEN detection_status IN ('New','Under Review') THEN 1 ELSE 0 END)   AS pending,
            SUM(CASE WHEN risk_level IN ('Critical','High')          THEN 1 ELSE 0 END)   AS high_risk,
            SUM(CASE WHEN detection_status IN ('Resolved','False Positive') THEN 1 ELSE 0 END) AS resolved
        FROM pfa_match_detections
    ")->fetch();

    return [
        'total'     => (int)$row['total'],
        'pending'   => (int)$row['pending'],
        'high_risk' => (int)$row['high_risk'],
        'resolved'  => (int)$row['resolved'],
    ];
}

// ─── Get Detections List (paginated) ─────────────────────────────────────────
function getDetections(PDO $pdo): array {
    $page    = max(1, (int)($_GET['page']     ?? 1));
    $perPage = max(1, (int)($_GET['per_page'] ?? PER_PAGE));
    $offset  = ($page - 1) * $perPage;

    // Optional filters
    $risk   = $_GET['risk']   ?? '';
    $status = $_GET['status'] ?? '';
    $search = trim($_GET['q'] ?? '');

    $where  = ['1=1'];
    $params = [];

    if ($risk) {
        $where[]           = 'd.risk_level = :risk';
        $params[':risk']   = $risk;
    }
    if ($status) {
        $where[]            = 'd.detection_status = :status';
        $params[':status']  = $status;
    }
    if ($search) {
        $where[]            = '(sh.search_term LIKE :q OR d.matched_full_name LIKE :q2)';
        $params[':q']       = "%$search%";
        $params[':q2']      = "%$search%";
    }

    $whereSQL = implode(' AND ', $where);

    // Total count
    $countStmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM pfa_match_detections d
        JOIN pfa_search_history sh ON sh.id = d.search_history_id
        WHERE $whereSQL
    ");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();

    // Rows
    $stmt = $pdo->prepare("
        SELECT
            d.id,
            CONCAT('DET-', LPAD(d.id, 11, '0')) AS detection_id,
            sh.search_term                        AS query,
            d.matched_full_name                   AS matched_entity,
            ROUND(d.match_score)                  AS score,
            d.risk_level,
            d.detection_status                    AS status,
            DATE_FORMAT(d.detected_at, '%b %d, %Y') AS created_date,
            d.search_history_id
        FROM pfa_match_detections d
        JOIN pfa_search_history sh ON sh.id = d.search_history_id
        WHERE $whereSQL
        ORDER BY
            CASE d.risk_level
                WHEN 'Critical' THEN 1
                WHEN 'High'     THEN 2
                WHEN 'Medium'   THEN 3
                ELSE 4
            END,
            d.detected_at DESC
        LIMIT :limit OFFSET :offset
    ");

    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v);
    }
    $stmt->bindValue(':limit',  $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset,  PDO::PARAM_INT);
    $stmt->execute();
    $rows = $stmt->fetchAll();

    return [
        'success'     => true,
        'detections'  => $rows,
        'stats'       => getStats($pdo),
        'total'       => $total,
        'total_pages' => (int)ceil($total / $perPage),
        'page'        => $page,
        'per_page'    => $perPage,
    ];
}

// ─── Get Single Detection + Related ──────────────────────────────────────────
function getDetectionDetails(PDO $pdo, int $id): array {
    if ($id <= 0) {
        return ['success' => false, 'error' => 'Invalid detection ID'];
    }

    // Main detection
    $stmt = $pdo->prepare("
        SELECT
            d.id,
            CONCAT('DET-', LPAD(d.id, 11, '0'))    AS detection_id,
            sh.search_term                           AS query,
            d.matched_full_name                      AS matched_entity,
            ROUND(d.match_score)                     AS score,
            d.match_confidence                       AS confidence,
            d.risk_level,
            d.detection_status                       AS status,
            d.matched_external_id                    AS external_id,
            d.matched_nationality                    AS nationality,
            DATE_FORMAT(d.matched_dob, '%Y-%m-%d')  AS dob,
            d.matched_status                         AS entity_status,
            d.matched_fields,
            d.score_breakdown,
            d.review_notes,
            DATE_FORMAT(d.detected_at, '%b %d, %Y %H:%i') AS created_date,
            d.search_history_id
        FROM pfa_match_detections d
        JOIN pfa_search_history sh ON sh.id = d.search_history_id
        WHERE d.id = :id
    ");
    $stmt->execute([':id' => $id]);
    $detection = $stmt->fetch();

    if (!$detection) {
        return ['success' => false, 'error' => 'Detection not found'];
    }

    // Decode JSON fields
    $detection['matched_fields']  = decodeField($detection['matched_fields'],  []);
    $detection['score_breakdown'] = decodeField($detection['score_breakdown'], []);

    // Related detections from same search
    $related = getRelatedDetections($pdo, (int)$detection['search_history_id'], $id);

    return [
        'success'             => true,
        'detection'           => $detection,
        'related_detections'  => $related,
    ];
}

// ─── Get Related Detections ───────────────────────────────────────────────────
function getRelatedDetections(PDO $pdo, int $searchHistoryId, int $excludeId): array {
    $stmt = $pdo->prepare("
        SELECT
            d.id,
            CONCAT('DET-', LPAD(d.id, 11, '0')) AS detection_id,
            d.matched_full_name                   AS matched_entity,
            ROUND(d.match_score)                  AS score,
            d.risk_level,
            d.detection_status                    AS status,
            d.matched_nationality                  AS nationality,
            d.matched_fields,
            DATE_FORMAT(d.detected_at, '%b %d, %Y') AS created_date
        FROM pfa_match_detections d
        WHERE d.search_history_id = :sid
          AND d.id != :exclude
        ORDER BY d.match_score DESC
    ");
    $stmt->execute([':sid' => $searchHistoryId, ':exclude' => $excludeId]);
    $rows = $stmt->fetchAll();

    foreach ($rows as &$row) {
        $row['matched_fields'] = decodeField($row['matched_fields'], []);
    }

    return $rows;
}

// ─── Update Status ────────────────────────────────────────────────────────────
function updateStatus(PDO $pdo, array $input): array {
    $id     = (int)($input['detection_id'] ?? 0);
    $status = trim($input['status']        ?? '');

    $allowed = ['New', 'Under Review', 'Reviewed', 'Confirmed', 'False Positive', 'Resolved', 'Ignored'];
    if ($id <= 0 || !in_array($status, $allowed)) {
        return ['success' => false, 'error' => 'Invalid parameters'];
    }

    $stmt = $pdo->prepare("
        UPDATE pfa_match_detections
        SET detection_status = :status,
            reviewed_at      = NOW()
        WHERE id = :id
    ");
    $stmt->execute([':status' => $status, ':id' => $id]);

    if ($stmt->rowCount() === 0) {
        return ['success' => false, 'error' => 'Detection not found'];
    }

    return [
        'success' => true,
        'message' => "Status updated to '$status'",
        'stats'   => getStats($pdo),
    ];
}

// ─── Helper ───────────────────────────────────────────────────────────────────
function decodeField($value, $fallback) {
    if (empty($value))              return $fallback;
    if (is_array($value))           return $value;
    $decoded = json_decode($value, true);
    return (json_last_error() === JSON_ERROR_NONE) ? $decoded : $fallback;
}
