<?php
/**
 * Notifications API
 * Handles notification-related API requests
 */

header('Content-Type: application/json');

session_start();
require_once '../db_connect.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];
$action = $_GET['action'] ?? $_POST['action'] ?? '';

switch ($action) {
    case 'count':
        // Get unread notification count
        $result = mysqli_query($conn, "
            SELECT COUNT(*) as count FROM cbc_notifications
            WHERE user_id = $user_id AND is_read = 0
        ");
        $row = mysqli_fetch_assoc($result);

        echo json_encode([
            'success' => true,
            'count' => intval($row['count'] ?? 0)
        ]);
        break;

    case 'recent':
        // Get recent notifications
        $limit = intval($_GET['limit'] ?? 5);
        $limit = min($limit, 20);

        $result = mysqli_query($conn, "
            SELECT n.*, l.land_name
            FROM cbc_notifications n
            LEFT JOIN lands l ON n.land_id = l.id
            WHERE n.user_id = $user_id
            ORDER BY n.created_at DESC
            LIMIT $limit
        ");

        $notifications = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $notifications[] = [
                'id' => $row['id'],
                'type' => $row['notification_type'],
                'title' => $row['title'],
                'message' => $row['message'],
                'land_id' => $row['land_id'],
                'land_name' => $row['land_name'],
                'is_read' => (bool)$row['is_read'],
                'created_at' => $row['created_at'],
                'time_ago' => timeAgo($row['created_at'])
            ];
        }

        // Get unread count
        $countResult = mysqli_query($conn, "
            SELECT COUNT(*) as count FROM cbc_notifications
            WHERE user_id = $user_id AND is_read = 0
        ");
        $countRow = mysqli_fetch_assoc($countResult);

        echo json_encode([
            'success' => true,
            'notifications' => $notifications,
            'unread_count' => intval($countRow['count'] ?? 0)
        ]);
        break;

    case 'mark_read':
        // Mark notification as read
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            echo json_encode(['success' => false, 'error' => 'Method not allowed']);
            exit;
        }

        $notification_id = intval($_POST['notification_id'] ?? 0);

        if ($notification_id > 0) {
            mysqli_query($conn, "
                UPDATE cbc_notifications SET is_read = 1, read_at = NOW()
                WHERE id = $notification_id AND user_id = $user_id
            ");

            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid notification ID']);
        }
        break;

    case 'mark_all_read':
        // Mark all notifications as read
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            echo json_encode(['success' => false, 'error' => 'Method not allowed']);
            exit;
        }

        mysqli_query($conn, "
            UPDATE cbc_notifications SET is_read = 1, read_at = NOW()
            WHERE user_id = $user_id AND is_read = 0
        ");

        echo json_encode(['success' => true]);
        break;

    default:
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
}

/**
 * Convert timestamp to human-readable time ago
 */
function timeAgo($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;

    if ($diff < 60) {
        return 'Just now';
    } elseif ($diff < 3600) {
        $mins = floor($diff / 60);
        return $mins . ' min' . ($mins > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 86400) {
        $hours = floor($diff / 3600);
        return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 604800) {
        $days = floor($diff / 86400);
        return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
    } else {
        return date('M j', $time);
    }
}
