<?php
require_once '../config/database.php';
header('Content-Type: application/json');

try {
    // Check if user is authenticated
    if (!isAuthenticated()) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        exit;
    }

    $id = $_POST['id'] ?? '';
    
    if (empty($id)) {
        echo json_encode(['success' => false, 'message' => 'Member ID is required']);
        exit;
    }

    $pdo = getDBConnection();

    // Check if members table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'members'");
    if ($stmt->rowCount() == 0) {
        echo json_encode(['success' => false, 'message' => 'Members table not found']);
        exit;
    }

    // Update member status to approved
    $stmt = $pdo->prepare("UPDATE members SET status = 'approved', approved_at = NOW(), approved_by = ? WHERE id = ?");
    $result = $stmt->execute([$_SESSION['user_id'] ?? 1, $id]);

    if ($result) {
        // Log the approval action
        $logStmt = $pdo->prepare("INSERT INTO activity_logs (user_id, action, description, created_at) VALUES (?, 'member_approved', ?, NOW())");
        $logStmt->execute([$_SESSION['user_id'] ?? 1, "Approved member with ID: $id"]);

        echo json_encode([
            'success' => true,
            'message' => 'Member approved successfully'
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to approve member']);
    }

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
