<?php
/**
 * PFA Dashboard API
 * Returns dashboard data matching the screenshot layout
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Database Configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'i4urunplace_xml');
define('DB_USER', 'i4urunplace_xml');
define('DB_PASS', 'SEMZtyETGL8B');

class DashboardAPI {
    private $pdo;
    
    public function __construct($dbHost, $dbName, $dbUser, $dbPass) {
        $this->connectDatabase($dbHost, $dbName, $dbUser, $dbPass);
    }
    
    private function connectDatabase($host, $dbName, $user, $pass) {
        try {
            $dsn = "mysql:host=$host;dbname=$dbName;charset=utf8mb4";
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            $this->pdo = new PDO($dsn, $user, $pass, $options);
        } catch (PDOException $e) {
            throw new Exception('Database connection failed: ' . $e->getMessage());
        }
    }
    
    /**
     * Get all dashboard data
     */
    public function getDashboardData() {
        return [
            'success' => true,
            'timestamp' => date('c'),
            'stats' => $this->getTopStats(),
            'recent_searches' => $this->getRecentSearches(),
            'recent_detections' => $this->getRecentDetections(),
            'alerts' => $this->getHighPriorityAlerts()
        ];
    }
    
    /**
     * Get top statistics cards
     */
    private function getTopStats() {
        $sql = "SELECT 
            (SELECT COUNT(*) FROM pfa_search_history) as total_searches,
            (SELECT COUNT(*) FROM pfa_search_history WHERE DATE(searched_at) = CURDATE()) as searches_today,
            (SELECT COUNT(*) 
             FROM pfa_match_detections 
             WHERE risk_level IN ('Critical', 'High') 
               AND detection_status IN ('New', 'Under Review')) as high_risk_detections,
            (SELECT COUNT(*) 
             FROM pfa_match_detections 
             WHERE detection_status IN ('New', 'Under Review')) as pending_reviews,
            (SELECT COUNT(*) 
             FROM pfa_records 
             WHERE active_status = 'Active') as active_records";
        
        $stmt = $this->pdo->query($sql);
        $data = $stmt->fetch();
        
        return [
            'total_searches' => [
                'value' => (int)$data['total_searches'],
                'subtitle' => $data['searches_today'] . ' today',
                'icon' => 'search'
            ],
            'high_risk_detections' => [
                'value' => (int)$data['high_risk_detections'],
                'subtitle' => 'Requires attention',
                'icon' => 'alert',
                'alert' => $data['high_risk_detections'] > 0
            ],
            'pending_reviews' => [
                'value' => (int)$data['pending_reviews'],
                'subtitle' => 'Awaiting action',
                'icon' => 'clock'
            ],
            'database_records' => [
                'value' => 'Active',
                'subtitle' => 'AML watchlist',
                'count' => (int)$data['active_records'],
                'icon' => 'database'
            ]
        ];
    }
    
    /**
     * Get recent searches
     */
    private function getRecentSearches($limit = 10) {
        $sql = "SELECT 
            sh.id,
            sh.search_term,
            sh.matched_results as matches_found,
            sh.searched_at,
            DATE_FORMAT(sh.searched_at, '%b %d, %H:%i') as formatted_date,
            sh.highest_score,
            CASE 
                WHEN sh.highest_score >= 95 THEN 'Critical'
                WHEN sh.highest_score >= 85 THEN 'High Risk'
                WHEN sh.highest_score >= 75 THEN 'Medium Risk'
                ELSE NULL
            END as risk_badge,
            (SELECT COUNT(*) 
             FROM pfa_match_detections d 
             WHERE d.search_history_id = sh.id 
               AND d.risk_level IN ('Critical', 'High')) as high_risk_count
        FROM pfa_search_history sh
        ORDER BY sh.searched_at DESC
        LIMIT :limit";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindValue('limit', $limit, PDO::PARAM_INT);
        $stmt->execute();
        
        $searches = [];
        while ($row = $stmt->fetch()) {
            $searches[] = [
                'id' => (int)$row['id'],
                'search_term' => $row['search_term'],
                'subtitle' => $row['matches_found'] . ' matches found',
                'matches_found' => (int)$row['matches_found'],
                'timestamp' => $row['formatted_date'],
                'risk_badge' => $row['risk_badge'],
                'has_high_risk' => (int)$row['high_risk_count'] > 0,
                'highest_score' => (float)$row['highest_score']
            ];
        }
        
        return $searches;
    }
    
    /**
     * Get recent detections
     */
    private function getRecentDetections($limit = 10) {
        $sql = "SELECT 
            d.id,
            d.matched_full_name,
            d.match_score,
            sh.search_term,
            d.detection_status,
            DATE_FORMAT(d.detected_at, '%b %d') as detected_date,
            d.risk_level
        FROM pfa_match_detections d
        JOIN pfa_search_history sh ON d.search_history_id = sh.id
        ORDER BY d.detected_at DESC
        LIMIT :limit";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindValue('limit', $limit, PDO::PARAM_INT);
        $stmt->execute();
        
        $detections = [];
        while ($row = $stmt->fetch()) {
            $detections[] = [
                'id' => (int)$row['id'],
                'person_name' => $row['matched_full_name'],
                'subtitle' => 'Query: "' . $row['search_term'] . '" • ' . round($row['match_score']) . '% match',
                'query' => $row['search_term'],
                'match_score' => (float)$row['match_score'],
                'status' => $this->formatStatus($row['detection_status']),
                'status_badge' => $this->getStatusBadge($row['detection_status']),
                'timestamp' => $row['detected_date'],
                'risk_level' => $row['risk_level']
            ];
        }
        
        return $detections;
    }
    
    /**
     * Get high priority alerts
     */
    private function getHighPriorityAlerts($limit = 5) {
        $sql = "SELECT 
            d.id,
            d.matched_full_name,
            d.match_score,
            d.risk_level,
            sh.search_term,
            DATE_FORMAT(d.detected_at, '%b %d, %Y %H:%i') as detected_time,
            DATEDIFF(NOW(), d.detected_at) as days_pending
        FROM pfa_match_detections d
        JOIN pfa_search_history sh ON d.search_history_id = sh.id
        WHERE d.risk_level IN ('Critical', 'High')
          AND d.detection_status = 'New'
        ORDER BY 
            CASE d.risk_level 
                WHEN 'Critical' THEN 1 
                WHEN 'High' THEN 2 
            END,
            d.detected_at ASC
        LIMIT :limit";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindValue('limit', $limit, PDO::PARAM_INT);
        $stmt->execute();
        
        return $stmt->fetchAll();
    }
    
    /**
     * Get search activity timeline
     */
    public function getSearchActivity($days = 7) {
        $sql = "SELECT 
            DATE(searched_at) as date,
            DATE_FORMAT(searched_at, '%b %d') as formatted_date,
            COUNT(*) as search_count,
            SUM(matched_results) as total_matches,
            AVG(search_duration_ms) as avg_duration_ms
        FROM pfa_search_history
        WHERE searched_at >= DATE_SUB(NOW(), INTERVAL :days DAY)
        GROUP BY DATE(searched_at)
        ORDER BY date DESC";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindValue('days', $days, PDO::PARAM_INT);
        $stmt->execute();
        
        return [
            'success' => true,
            'data' => $stmt->fetchAll()
        ];
    }
    
    /**
     * Get detection status breakdown
     */
    public function getDetectionBreakdown() {
        $sql = "SELECT 
            detection_status,
            COUNT(*) as count,
            ROUND(AVG(match_score), 1) as avg_score
        FROM pfa_match_detections
        GROUP BY detection_status
        ORDER BY 
            CASE detection_status
                WHEN 'New' THEN 1
                WHEN 'Under Review' THEN 2
                WHEN 'Reviewed' THEN 3
                WHEN 'Confirmed' THEN 4
                WHEN 'False Positive' THEN 5
                ELSE 6
            END";
        
        $stmt = $this->pdo->query($sql);
        
        return [
            'success' => true,
            'data' => $stmt->fetchAll()
        ];
    }
    
    /**
     * Get risk level distribution
     */
    public function getRiskDistribution() {
        $sql = "SELECT 
            risk_level,
            COUNT(*) as count,
            ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM pfa_match_detections), 1) as percentage
        FROM pfa_match_detections
        GROUP BY risk_level
        ORDER BY 
            CASE risk_level
                WHEN 'Critical' THEN 1
                WHEN 'High' THEN 2
                WHEN 'Medium' THEN 3
                WHEN 'Low' THEN 4
            END";
        
        $stmt = $this->pdo->query($sql);
        
        return [
            'success' => true,
            'data' => $stmt->fetchAll()
        ];
    }
    
    /**
     * Format detection status for display
     */
    private function formatStatus($status) {
        $map = [
            'New' => 'New',
            'Under Review' => 'Under Review',
            'Reviewed' => 'Reviewed',
            'Confirmed' => 'Confirmed',
            'False Positive' => 'Cleared',
            'Ignored' => 'Ignored'
        ];
        
        return $map[$status] ?? $status;
    }
    
    /**
     * Get status badge style
     */
    private function getStatusBadge($status) {
        $badges = [
            'New' => ['text' => 'New', 'color' => 'dark'],
            'Under Review' => ['text' => 'Under Review', 'color' => 'warning'],
            'Reviewed' => ['text' => 'Reviewed', 'color' => 'info'],
            'Confirmed' => ['text' => 'Confirmed', 'color' => 'danger'],
            'False Positive' => ['text' => 'Cleared', 'color' => 'success'],
            'Ignored' => ['text' => 'Ignored', 'color' => 'secondary']
        ];
        
        return $badges[$status] ?? ['text' => $status, 'color' => 'secondary'];
    }
}

// Handle API Request
try {
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Get database credentials
        $dbHost = $_GET['db_host'] ?? DB_HOST;
        $dbName = $_GET['db_name'] ?? DB_NAME;
        $dbUser = $_GET['db_user'] ?? DB_USER;
        $dbPass = $_GET['db_pass'] ?? DB_PASS;
        
        $api = new DashboardAPI($dbHost, $dbName, $dbUser, $dbPass);
        
        // Get action parameter
        $action = $_GET['action'] ?? 'dashboard';
        
        switch ($action) {
            case 'dashboard':
                $result = $api->getDashboardData();
                break;
                
            case 'activity':
                $days = $_GET['days'] ?? 7;
                $result = $api->getSearchActivity($days);
                break;
                
            case 'status_breakdown':
                $result = $api->getDetectionBreakdown();
                break;
                
            case 'risk_distribution':
                $result = $api->getRiskDistribution();
                break;
                
            default:
                $result = [
                    'success' => false,
                    'error' => 'Unknown action'
                ];
        }
        
        echo json_encode($result, JSON_PRETTY_PRINT);
        
    } else {
        http_response_code(405);
        echo json_encode([
            'success' => false,
            'error' => 'Method not allowed'
        ]);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
