<?php
/**
 * API: Mark notification as read
 * 
 * This endpoint marks a notification as read for a specific user
 */

require_once '../../config/database.php';
requireAdmin();

// Default response structure
$response = [
    'success' => false,
    'data' => null,
    'message' => 'Error marking notification as read'
];

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Method not allowed';
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

try {
    // Get POST data
    $postData = json_decode(file_get_contents('php://input'), true);
    if (!$postData) {
        $postData = $_POST;
    }
    
    // Validate required fields
    if (!isset($postData['notification_id']) || empty($postData['notification_id'])) {
        throw new Exception("Field 'notification_id' is required");
    }
    
    $db = new Database();
    $conn = $db->getConnection();
    
    $notificationId = $postData['notification_id'];
    $userId = $_SESSION['admin_id']; // Get from session
    $userType = 'admin';
    
    // Check if record exists
    $checkQuery = "SELECT id FROM notification_recipients 
                   WHERE notification_id = :notification_id 
                   AND user_id = :user_id 
                   AND user_type = :user_type";
    $checkStmt = $conn->prepare($checkQuery);
    $checkStmt->bindValue(':notification_id', $notificationId);
    $checkStmt->bindValue(':user_id', $userId);
    $checkStmt->bindValue(':user_type', $userType);
    $checkStmt->execute();
    
    if ($checkStmt->rowCount() > 0) {
        // Update existing record
        $query = "UPDATE notification_recipients 
                  SET is_read = 1, read_at = NOW() 
                  WHERE notification_id = :notification_id 
                  AND user_id = :user_id 
                  AND user_type = :user_type";
        $stmt = $conn->prepare($query);
        $stmt->bindValue(':notification_id', $notificationId);
        $stmt->bindValue(':user_id', $userId);
        $stmt->bindValue(':user_type', $userType);
        $stmt->execute();
    } else {
        // Insert new record
        $query = "INSERT INTO notification_recipients 
                  (notification_id, user_id, user_type, is_read, read_at) 
                  VALUES 
                  (:notification_id, :user_id, :user_type, 1, NOW())";
        $stmt = $conn->prepare($query);
        $stmt->bindValue(':notification_id', $notificationId);
        $stmt->bindValue(':user_id', $userId);
        $stmt->bindValue(':user_type', $userType);
        $stmt->execute();
    }
    
    // Check if all recipients have read this notification
    $allReadQuery = "SELECT 
                      (SELECT COUNT(*) FROM notification_recipients WHERE notification_id = :notification_id) as total,
                      (SELECT COUNT(*) FROM notification_recipients WHERE notification_id = :notification_id AND is_read = 1) as read_count";
    $allReadStmt = $conn->prepare($allReadQuery);
    $allReadStmt->bindValue(':notification_id', $notificationId);
    $allReadStmt->execute();
    $readStats = $allReadStmt->fetch(PDO::FETCH_ASSOC);
    
    // If all recipients have read, update the main notification
    if ($readStats['total'] > 0 && $readStats['total'] == $readStats['read_count']) {
        $updateNotificationQuery = "UPDATE notifications 
                                   SET is_read = 1, read_at = NOW() 
                                   WHERE id = :notification_id";
        $updateNotificationStmt = $conn->prepare($updateNotificationQuery);
        $updateNotificationStmt->bindValue(':notification_id', $notificationId);
        $updateNotificationStmt->execute();
    }
    
    // Format the response
    $response = [
        'success' => true,
        'data' => [
            'notification_id' => $notificationId,
            'is_read' => true,
            'read_at' => date('Y-m-d H:i:s')
        ],
        'message' => 'Notification marked as read successfully'
    ];
    
} catch (PDOException $e) {
    $response['message'] = 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
    $response['message'] = 'Error: ' . $e->getMessage();
}

// Send JSON response
header('Content-Type: application/json');
echo json_encode($response);
exit;
