<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth_middleware.php';

// Enforce view permission for activity logs
$pageKey = 'activity_logs';
checkApiPagePermission($pageKey, 'view');

$action = isset($_GET['action']) ? $_GET['action'] : '';

// Helper function to safely bind dynamic parameters by reference
function bindDynamicParams($stmt, $types, $params) {
    if (empty($types) || empty($params)) return;
    $refs = [$types];
    foreach ($params as $key => $value) {
        $refs[] = &$params[$key];
    }
    call_user_func_array([$stmt, 'bind_param'], $refs);
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if ($action === 'list') {
        $search = isset($_GET['search']) ? trim($_GET['search']) : '';
        $filter_action = isset($_GET['filter_action']) ? trim($_GET['filter_action']) : '';
        $filter_table = isset($_GET['filter_table']) ? trim($_GET['filter_table']) : '';
        $from_date = isset($_GET['from_date']) ? trim($_GET['from_date']) : '';
        $to_date = isset($_GET['to_date']) ? trim($_GET['to_date']) : '';

        $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        $limit = isset($_GET['limit']) ? max(5, (int)$_GET['limit']) : 10;
        $offset = ($page - 1) * $limit;

        $whereClauses = [];
        $params = [];
        $types = "";

        if (!empty($search)) {
            $whereClauses[] = "(u.name LIKE ? OR u.username LIKE ? OR CAST(l.record_id AS CHAR) LIKE ? OR l.action LIKE ? OR l.table_name LIKE ? OR l.details LIKE ?)";
            $searchWild = "%" . $search . "%";
            $params = array_merge($params, [$searchWild, $searchWild, $searchWild, $searchWild, $searchWild, $searchWild]);
            $types .= "ssssss";
        }

        if (!empty($filter_action)) {
            $whereClauses[] = "l.action = ?";
            $params[] = $filter_action;
            $types .= "s";
        }

        if (!empty($filter_table)) {
            $whereClauses[] = "l.table_name = ?";
            $params[] = $filter_table;
            $types .= "s";
        }

        if (!empty($from_date)) {
            $whereClauses[] = "DATE(l.created_at) >= ?";
            $params[] = $from_date;
            $types .= "s";
        }

        if (!empty($to_date)) {
            $whereClauses[] = "DATE(l.created_at) <= ?";
            $params[] = $to_date;
            $types .= "s";
        }

        $whereSql = "";
        if (!empty($whereClauses)) {
            $whereSql = " WHERE " . implode(" AND ", $whereClauses);
        }

        // Base parameters before pagination
        $baseParams = $params;
        $baseTypes = $types;

        // Count query for pagination
        $countQuery = "SELECT COUNT(*) AS total FROM activity_logs l LEFT JOIN users u ON l.user_id = u.id" . $whereSql;
        $stmt = $conn->prepare($countQuery);
        if (!empty($baseTypes) && !empty($baseParams)) {
            bindDynamicParams($stmt, $baseTypes, $baseParams);
        }
        $stmt->execute();
        $total = (int)$stmt->get_result()->fetch_assoc()['total'];
        $stmt->close();

        // Data query
        $dataQuery = "
            SELECT l.*, COALESCE(u.name, 'مستخدم محذوف') AS user_fullname, COALESCE(u.username, '-') AS user_username
            FROM activity_logs l
            LEFT JOIN users u ON l.user_id = u.id
            $whereSql
            ORDER BY l.id DESC
            LIMIT ? OFFSET ?
        ";
        
        $dataParams = array_merge($baseParams, [$limit, $offset]);
        $dataTypes = $baseTypes . "ii";

        $stmt = $conn->prepare($dataQuery);
        bindDynamicParams($stmt, $dataTypes, $dataParams);
        $stmt->execute();
        $res = $stmt->get_result();
        $logs = [];
        while ($row = $res->fetch_assoc()) {
            $logs[] = [
                "id" => $row['id'],
                "userId" => $row['user_id'],
                "userFullname" => $row['user_fullname'],
                "userUsername" => $row['user_username'],
                "action" => $row['action'],
                "tableName" => $row['table_name'],
                "recordId" => $row['record_id'],
                "details" => json_decode($row['details'], true) ?: new stdClass(),
                "createdAt" => $row['created_at']
            ];
        }
        $stmt->close();

        // Filter-aware Stats counts
        $statsQuery = "SELECT l.action, COUNT(*) AS cnt FROM activity_logs l LEFT JOIN users u ON l.user_id = u.id" . $whereSql . " GROUP BY l.action";
        $sStmt = $conn->prepare($statsQuery);
        if (!empty($baseTypes) && !empty($baseParams)) {
            bindDynamicParams($sStmt, $baseTypes, $baseParams);
        }
        $sStmt->execute();
        $stats_res = $sStmt->get_result();

        $stats = [
            "total" => 0,
            "insert" => 0,
            "update" => 0,
            "delete" => 0,
            "payment" => 0
        ];
        if ($stats_res) {
            while ($row = $stats_res->fetch_assoc()) {
                $act = $row['action'];
                $cnt = (int)$row['cnt'];
                $stats['total'] += $cnt;
                if (isset($stats[$act])) {
                    $stats[$act] = $cnt;
                } else {
                    $stats[$act] = $cnt;
                }
            }
        }
        $sStmt->close();

        echo json_encode([
            "status" => "success",
            "total" => $total,
            "page" => $page,
            "limit" => $limit,
            "stats" => $stats,
            "data" => $logs
        ]);
        exit;
    }
}

echo json_encode(["status" => "error", "message" => "طلب غير صالح"]);
exit;
?>
